﻿using Chemistry.Models;
using OPCAutomation;
using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Text;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Documents;
using GLCommon;

namespace Chemistry.WorkFlow
{
    /// <summary>
    /// 聚丙烯生产聚合自控流程
    /// </summary>
    public class Polypropylene : FlowBaseAll
    {
        #region 字段
        private int _sleepfast = 500;
        private int _relay_command = 0;

        double _pressure_value ;
        double _temperature_value = 22;
        double _flow_value ;
        int _reaction_second = 20;//反应时间（分钟）
        double _h2_flow;

        //初始值 用来被减去的值
       double _total_pressure_h2 ;
       double _total_pressure_hopper;
       double _total_weight1 ;
       double _total_weight2;
       double _pressure_h2 ;
       
       double _pressure_hopper ;
       double _weight_left1 ;
       double _weight_left2 ;
       double _weight_right ;

        int open = 1;//0-48
        int close = 0;//1-49

        bool _isgetoverstate1 = false;
        bool _isgetoverstate2 = false;
        bool _isgetoverstate3 = false;

        double _temperature_increment ;
        double _temperature_decrement ;
        double _pressure_increment ;
        double _pressure_decrement;
        double _pressure_hopper_crement;
        double _h2_flow_crement;
        //命令
        private Tools.Tool.FlowCommand _flowcommand;
        string _switch1 = string.Empty;
        string _switch2 = string.Empty;
        string _prefix1 = string.Empty;
        string _prefix2 = string.Empty;
        string _prefix3 = string.Empty;
        string _llcmd = string.Empty;
        string _wdcmd = string.Empty;
        string _ywcmd = string.Empty;
        string _ylcmd = string.Empty;
        string _heightcmd = string.Empty;
        string _leftHeightCmd = string.Empty;
        string _rightHeightCmd = string.Empty;
        string _aicmd = string.Empty;
        string _relaycmd = string.Empty;
        int _warning1number ;
        int _warning2number;
        int _fognumber ;
        int _stirnumber;
        #endregion

        #region 与组态对应的阀门状态
        //开关状态
        bool _valveLeftEmptyState = false;
        bool _valveOutO2State = false;
        bool _valveInActivatorState = false;
        bool _valveInColdState = false;
        bool _valveInColdSecondState = false;
        bool _valveInGasState = false;
        bool _valveInH2State = false;
        bool _valveInHotState = false;
        bool _valveInN2RightState = false;
        bool _valveInPropyleneLeftState = false;
        bool _valveInPropyleneRightState = false;
        bool _valveLeftHopperState = false;
        //static bool ValveOutCold_State = false;
         bool _valveOutGas_State = false;
        //static bool ValveOutHot_State = false;
         bool _valveOutPropyleneState = false;
         bool _valveOutPropyleneWithHopperState ;
         bool _valveRightHopperState = false;
        //static bool ValveEmptyFromHopper_State = false;
        //static bool ValveInDownPropylene_State = false;
         bool _valveStirState = false;
         bool _valveStopState = false;

        #endregion

        #region OPCItem
        //阀门
        OPCItem ValveLeftEmpty_item;
        /// <summary>
        /// 放空总管
        /// </summary>
        OPCItem ValveOutO2_item;
        OPCItem ValveInActivator_item;
        OPCItem ValveInCold_item;
        OPCItem ValveInColdSecond_item;
        /// <summary>
        /// 气相丙烯
        /// </summary>
        OPCItem ValveInGas_item;
        OPCItem ValveInH2_item;
        OPCItem ValveInHot_item;
        OPCItem ValveInN2Right_item;
        OPCItem ValveInPropyleneLeft_item;
        OPCItem ValveInPropyleneRight_item;
        OPCItem ValveLeftHopper_item;
        OPCItem ValveOutCold_item;
        OPCItem ValveOutGas_item;
        OPCItem ValveOutHot_item;
        OPCItem ValveOutPropylene_item;
        OPCItem ValveOutPropyleneWithHopper_item;
        OPCItem ValveRightHopper_item;
        OPCItem ValveInDownPropylene_item;
        OPCItem ValveEmptyFromHopper_item;
        OPCItem ValveStir_item;
        OPCItem ValveStop_item;
        //管道
        OPCItem FlowOutO2_item;
        OPCItem FlowInPropylene_item;
        OPCItem FlowInActivator_item;
        OPCItem FlowInN2_item;
        OPCItem FlowInCold_item;
        OPCItem FlowInColdSecond_item;
        OPCItem FlowInGas_item;
        OPCItem FlowInH2_item;
        OPCItem FlowInHot_item;
        OPCItem FlowInLeft_item;
        OPCItem FlowInPropyleneRight_item;
        OPCItem FlowInRight_item;
        OPCItem FlowOutActivator_item;
        OPCItem FlowLeftEmpty_item;
        OPCItem FlowOutPropylene_item;
        OPCItem FlowOutCold_item;
        OPCItem FlowOutGas_item;
        OPCItem FlowOutHot_item;
        OPCItem FlowOutGasFomKettle_item;
        OPCItem FlowInPropyleneDown_item;
        OPCItem FlowRightEmpty_item;

        //label
        OPCItem LabelPressure_item;
        OPCItem LabelTemperature_item;
        OPCItem LabelFlow_item;
        OPCItem LabelContent_item;
        OPCItem LabelH2press_item;
        OPCItem LabelWeight1_item;
        OPCItem LabelWeight2_item;
        OPCItem LabelPressureHopper_item;//活化剂压力

        //闪烁
        OPCItem FlashKettle_item;
        OPCItem FlashPressure_item;
        OPCItem FlashTemperature_item;
        OPCItem FlashHopperPressure_item;
        OPCItem FlashWarning_item;
        #endregion

        #region 初始化

        public Polypropylene(OPCServer opcserver, SerialPort port,bool isinner)
        {
            _opcServer = opcserver;
            _serialPort = port;
            Isinner = isinner;
            
            InitFiled();
            InitOPC();
            InitOPCItem();
            InitSignal();
        }
        public Polypropylene(OPCServer opcserver, SerialPort port, bool isinner, bool isSlow)
        {
            _opcServer = opcserver;
            _serialPort = port;
            Isinner = isinner;
            IsExamSpeed = isSlow;

            InitFiled();
            InitOPC();
            InitOPCItem();
            InitSignal();
        }

        private async Task InitServerData()
        {
            _details = await GetDetailList(GetType().Name);
        }

        private void InitFlowCommandData()
        {
            _flowcommand = Tools.Tool.GetFlowCommand(this.GetType().Name);
            _switch1 = _flowcommand.Items.SingleOrDefault(i => i.Name == "switch1").Value;
            _switch2 = _flowcommand.Items.SingleOrDefault(i => i.Name == "switch2").Value;
            _prefix1 = _flowcommand.Items.SingleOrDefault(i => i.Name == "prefix1").Value;
            _prefix2 = _flowcommand.Items.SingleOrDefault(i => i.Name == "prefix2").Value;
            _prefix3 = _flowcommand.Items.SingleOrDefault(i => i.Name == "prefix3").Value;
            _llcmd = _flowcommand.Items.SingleOrDefault(i => i.Name == "llcmd").Value;
            _ywcmd = _flowcommand.Items.SingleOrDefault(i => i.Name == "ywcmd").Value;
            _ylcmd = _flowcommand.Items.SingleOrDefault(i => i.Name == "ylcmd").Value;
            _leftHeightCmd = _flowcommand.Items.SingleOrDefault(i => i.Name == "leftheightcmd").Value;
            _rightHeightCmd = _flowcommand.Items.SingleOrDefault(i => i.Name == "rightheightcmd").Value;
            _wdcmd = _flowcommand.Items.SingleOrDefault(i => i.Name == "wdcmd").Value;
            _aicmd = _flowcommand.Items.SingleOrDefault(i => i.Name == "aicmd").Value;
            _relaycmd = _flowcommand.Items.SingleOrDefault(i => i.Name == "relaycmd").Value;
            _warning1number = int.Parse(_flowcommand.Items.SingleOrDefault(i => i.Name == "warning1").Value);
            _warning2number = int.Parse(_flowcommand.Items.SingleOrDefault(i => i.Name == "warning2").Value);
            _fognumber = int.Parse(_flowcommand.Items.SingleOrDefault(i => i.Name == "fog").Value);
            _stirnumber = int.Parse(_flowcommand.Items.SingleOrDefault(i => i.Name == "stir").Value);

        }

        private void InitSignal()
        {
            if (Isinner)
            {
                ListenSignal();
                open = 1;
                close = 0;
            }
            else
            {
                InitFlowCommandData();
                _serialPort.DataReceived += _serialPort_DataReceived;
                InitOPCItemWithSerialPort();
                ListenSerialPort();
                open = 48;
                close = 49;
            }
        }

        private void InitFiled()
        {
            _pressure_value = 0;
            _temperature_value = 22;
            _flow_value =25;
            _h2_flow = 0;

            _total_pressure_h2 = 0.3;
            _total_pressure_hopper = 0.3;
            _total_weight1 = 6000;
            _total_weight2 = 6000;
            _pressure_h2 = 0;
            _pressure_hopper = 0;
            _weight_left1 = 0;
            _weight_left2 = 0;
            _weight_right = 0;

            _isgetoverstate1 = false;
            _isgetoverstate2 = false;
            _isgetoverstate3 = false;

            _temperature_increment = 1;
            _temperature_decrement = 0.5;
            _pressure_increment = 0.01;
            _pressure_decrement = 0.04;
            _pressure_hopper_crement = 0.01;
            _h2_flow_crement = 2;
        }

        private void InitOPCItemWithSerialPort()
        {
            SpLeftHeightValue(_total_weight1);//左侧丙烯重量
            SpPressureValue(_pressure_value);//压力
            SpRightHeightValue( _total_weight2);//右侧丙烯重量
            SpTemperatureValue(_temperature_value);//温度
            SpFlowValue(_h2_flow);
        }

        
        private void InitOPCItem()
        {
            //阀门
            ValveLeftEmpty_item = GetItem(FieldName.ValveLeftEmpty); ValveLeftEmpty_item.Close();
            ValveOutO2_item = GetItem(FieldName.ValveOutO2); ValveOutO2_item.Close();
            ValveInActivator_item = GetItem(FieldName.ValveInActivator); ValveInActivator_item.Close();
            ValveInCold_item = GetItem(FieldName.ValveInCold); ValveInCold_item.Close();
            ValveInColdSecond_item = GetItem(FieldName.ValveInColdSecond); ValveInColdSecond_item.Close();
            ValveInGas_item = GetItem(FieldName.ValveInGas); ValveInGas_item.Close();
            ValveInH2_item = GetItem(FieldName.ValveInH2); ValveInH2_item.Close();
            ValveInHot_item = GetItem(FieldName.ValveInHot); ValveInHot_item.Close();
            ValveInN2Right_item = GetItem(FieldName.ValveInN2Right); ValveInN2Right_item.Close();
            ValveInPropyleneLeft_item = GetItem(FieldName.ValveInPropyleneLeft); ValveInPropyleneLeft_item.Close();
            ValveInPropyleneRight_item = GetItem(FieldName.ValveInPropyleneRight); ValveInPropyleneRight_item.Close();
            ValveLeftHopper_item = GetItem(FieldName.ValveLeftHopper); ValveLeftHopper_item.Close();
            ValveOutCold_item = GetItem(FieldName.ValveOutCold); ValveOutCold_item.Close();
            ValveOutGas_item = GetItem(FieldName.ValveOutGas); ValveOutGas_item.Close();
            ValveOutHot_item = GetItem(FieldName.ValveOutHot); ValveOutHot_item.Close();
            ValveOutPropylene_item = GetItem(FieldName.ValveOutPropylene); ValveOutPropylene_item.Close();
            ValveOutPropyleneWithHopper_item = GetItem(FieldName.ValveOutPropyleneWithHopper); ValveOutPropyleneWithHopper_item.Close();
            ValveRightHopper_item = GetItem(FieldName.ValveRightHopper); ValveRightHopper_item.Close();
            ValveInDownPropylene_item = GetItem(FieldName.ValveInDownPropylene); ValveInDownPropylene_item.Close();
            ValveEmptyFromHopper_item = GetItem(FieldName.ValveEmptyFromHopper); ValveEmptyFromHopper_item.Close();
            ValveStir_item = GetItem(FieldName.ValveStir); ValveStir_item.Close();
            ValveStop_item = GetItem(FieldName.ValveStop); ValveStop_item.Close();

            //管道
            FlowOutO2_item = GetItem(FieldName.FlowOutO2); FlowOutO2_item.Close();
            FlowInPropylene_item = GetItem(FieldName.FlowInPropylene); FlowInPropylene_item.Close();
            FlowInActivator_item = GetItem(FieldName.FlowInActivator); FlowInActivator_item.Close();
            FlowInN2_item = GetItem(FieldName.FlowInN2); FlowInN2_item.Close();
            FlowInCold_item = GetItem(FieldName.FlowInCold); FlowInCold_item.Close();
            FlowInColdSecond_item = GetItem(FieldName.FlowInColdSecond); FlowInColdSecond_item.Close();
            FlowInGas_item = GetItem(FieldName.FlowInGas); FlowInGas_item.Close();
            FlowInH2_item = GetItem(FieldName.FlowInH2); FlowInH2_item.Close();
            FlowInHot_item = GetItem(FieldName.FlowInHot); FlowInHot_item.Close();
            FlowInLeft_item = GetItem(FieldName.FlowInLeft); FlowInLeft_item.Close();
            FlowInPropyleneRight_item = GetItem(FieldName.FlowInPropyleneRight); FlowInPropyleneRight_item.Close();
            FlowInRight_item = GetItem(FieldName.FlowInRight); FlowInRight_item.Close();
            FlowOutActivator_item = GetItem(FieldName.FlowOutActivator); FlowOutActivator_item.Close();
            FlowLeftEmpty_item = GetItem(FieldName.FlowLeftEmpty); FlowLeftEmpty_item.Close();
            FlowOutPropylene_item = GetItem(FieldName.FlowOutPropylene); FlowOutPropylene_item.Close();
            FlowOutCold_item = GetItem(FieldName.FlowOutCold); FlowOutCold_item.Close();
            FlowOutGas_item = GetItem(FieldName.FlowOutGas); FlowOutGas_item.Close();
            FlowOutHot_item = GetItem(FieldName.FlowOutHot); FlowOutHot_item.Close();
            FlowOutGasFomKettle_item = GetItem(FieldName.FlowOutGasFomKettle); FlowOutGasFomKettle_item.Close();
            FlowInPropyleneDown_item = GetItem(FieldName.FlowInPropyleneDown); FlowInPropyleneDown_item.Close();
            FlowRightEmpty_item = GetItem(FieldName.FlowRightEmpty); FlowRightEmpty_item.Close();

            //label
            LabelPressure_item = GetItem(FieldName.LabelPressure); LabelPressure_item.Write(_pressure_value);
            LabelTemperature_item = GetItem(FieldName.LabelTemperature); LabelTemperature_item.Write(_temperature_value);
            LabelFlow_item = GetItem(FieldName.LabelFlow); LabelFlow_item.Write(0);
            LabelContent_item = GetItem(FieldName.LabelContent); LabelContent_item.Write(0);
            LabelH2press_item = GetItem(FieldName.LabelH2press); LabelH2press_item.Write(_total_pressure_hopper);
            LabelWeight1_item = GetItem(FieldName.LabelWeight1); LabelWeight1_item.Write(_total_weight1);
            LabelWeight2_item = GetItem(FieldName.LabelWeight2); LabelWeight2_item.Write(_total_weight1);
            LabelPressureHopper_item = GetItem(FieldName.LabelPressureHopper); LabelPressureHopper_item.Write(_total_pressure_hopper);//活化剂压力

            //闪烁
            FlashKettle_item = GetItem(FieldName.FlashKettle); FlashKettle_item.StopFlow();
            FlashPressure_item = GetItem(FieldName.FlashPressure); FlashPressure_item.Close();
            FlashTemperature_item = GetItem(FieldName.FlashTempreture); FlashTemperature_item.Close();
            FlashHopperPressure_item = GetItem(FieldName.FlashHopperPressure); FlashHopperPressure_item.Close();
            FlashWarning_item = GetItem(FieldName.FlashWarning); FlashWarning_item.Close();
        }
        #endregion

        #region 监听步骤，计分
        private void ListenSerialPort()
        {
            string chkcmd_1 = _flowcommand.Items.SingleOrDefault(i => i.Name == "chkcmd1").Value;  //"#RYW11651&";
            string chkcmd_2 = _flowcommand.Items.SingleOrDefault(i => i.Name == "chkcmd2").Value;//"#RYW11652&";
            string chkcmd_3 = _flowcommand.Items.SingleOrDefault(i => i.Name == "chkcmd3").Value;//"#RYW11653&";


            Task listSerialPortState = new Task(
                () =>
                {
                    while (!_listenCts.IsCancellationRequested)
                    {
                        SendScannerCmd(chkcmd_1);
                        Thread.Sleep(200);
                        SendScannerCmd(chkcmd_2);
                        Thread.Sleep(200);
                        SendScannerCmd(chkcmd_3);
                        Thread.Sleep(200);
                    }
                });
            listSerialPortState.Start();
        }

        void SendScannerCmd(string cmd)
        {
            try
            {
                if (!_serialPort.IsOpen) return;
                lock (this)
                {
                    _serialPort.Write(cmd);
                }
            }
            catch (Exception)
            {
            }
        }

        bool _isListenSingnalover;
        int _replace_count = 1;//丙烯置换次数
        bool _can_open_empty = false;
        int _propylene_number = 1;//左侧充丙烯次数
        bool _can_fill_second_propylene = false;
        bool _can_fill_propylene = false;
        private void ListenSignal()
        {
            Task t = new Task(() =>
            {
                while (!_listenCts.IsCancellationRequested)
                {
                    int ValveLeftEmpty = Convert.ToInt32(ReadItem(FieldName.ValveLeftEmpty));
                    int ValveOutO2 = Convert.ToInt32(ReadItem(FieldName.ValveOutO2));
                    int ValveInActivator = Convert.ToInt32(ReadItem(FieldName.ValveInActivator));
                    int ValveInCold = Convert.ToInt32(ReadItem(FieldName.ValveInCold));
                    int ValveInColdSecond = Convert.ToInt32(ReadItem(FieldName.ValveInColdSecond));
                    int ValveInGas = Convert.ToInt32(ReadItem(FieldName.ValveInGas));
                    int ValveInH2 = Convert.ToInt32(ReadItem(FieldName.ValveInH2));
                    int ValveInHot = Convert.ToInt32(ReadItem(FieldName.ValveInHot));
                    int ValveInN2 = Convert.ToInt32(ReadItem(FieldName.ValveInN2Right));
                    int ValveInN2Left = Convert.ToInt32(ReadItem(FieldName.ValveInN2Left));
                    int ValveInPropylene = Convert.ToInt32(ReadItem(FieldName.ValveInPropyleneLeft));
                    int ValveInPropyleneRight = Convert.ToInt32(ReadItem(FieldName.ValveInPropyleneRight));
                    int ValveLeftHopper = Convert.ToInt32(ReadItem(FieldName.ValveLeftHopper));
                    int ValveOutCold = Convert.ToInt32(ReadItem(FieldName.ValveOutCold));
                    int ValveOutGas = Convert.ToInt32(ReadItem(FieldName.ValveOutGas));
                    int ValveOutHot = Convert.ToInt32(ReadItem(FieldName.ValveOutHot));
                    int ValveOutPropylene = Convert.ToInt32(ReadItem(FieldName.ValveOutPropylene));
                    int ValveOutPropyleneWithHopper = Convert.ToInt32(ReadItem(FieldName.ValveOutPropyleneWithHopper));
                    int ValveRightHopper = Convert.ToInt32(ReadItem(FieldName.ValveRightHopper));
                    int ValveInDownPropylene = Convert.ToInt32(ReadItem(FieldName.ValveInDownPropylene));
                    int ValveEmptyFromHopper = Convert.ToInt32(ReadItem(FieldName.ValveEmptyFromHopper));
                    int ValveStir = Convert.ToInt32(ReadItem(FieldName.ValveStir));
                    int ValveStop = Convert.ToInt32(ReadItem(FieldName.ValveStop));

                    _valveLeftEmptyState = ValveLeftEmpty == open;
                    _valveOutO2State = ValveOutO2 == open;
                    _valveInActivatorState = ValveInActivator == open;
                    _valveInColdState = ValveInCold == open;
                    _valveInColdSecondState = ValveInColdSecond == open;
                    _valveInGasState = ValveInGas == open;
                    _valveInH2State = ValveInH2 == open;
                    _valveInHotState = ValveInHot == open;
                    _valveInN2RightState = ValveInN2 == open;
                    _valveInPropyleneLeftState = ValveInPropylene == open;
                    _valveInPropyleneRightState = ValveInPropyleneRight == open;
                    _valveLeftHopperState = ValveLeftHopper == open;
                    //ValveOutCold_State = ValveOutCold == open;
                    _valveOutGas_State = ValveOutGas == open;
                    //ValveOutHot_State = ValveOutHot == open;
                    _valveOutPropyleneState = ValveOutPropylene == open;
                    _valveOutPropyleneWithHopperState = ValveOutPropyleneWithHopper == open;
                    _valveRightHopperState = ValveRightHopper == open;
                    //ValveInDownPropylene_State = ValveInDownPropylene == open;
                    //ValveEmptyFromHopper_State = ValveEmptyFromHopper == open;
                    _valveStirState = ValveStir == open;
                    _valveStopState = ValveStop == open;

                    DateTime now = DateTime.Now;
                    Step step = new Step()
                    {
                        Status = new Dictionary<Enum, double>()
                        {
                                {StatusName.丙烯总量,ValveInGas},
                                {StatusName.反应釜压力,_pressure_value},
                                {StatusName.冷水阀辅 , ValveInColdSecond},
                                {StatusName.冷水阀主,ValveInCold},
                                {StatusName.冷水回水阀,ValveOutCold},
                                {StatusName.气相丙烯阀1,-1},
                                {StatusName.气相丙烯阀2,-1},
                                {StatusName.气相丙烯阀3,-1},
                                {StatusName.氢气阀,ValveInH2},
                                {StatusName.热水阀,ValveInHot},
                                {StatusName.热水回水阀,ValveOutHot},
                                {StatusName.温度,_temperature_value},

                                {StatusName.右侧丙烯重量, _weight_right},
                                {StatusName.右侧氮气阀,ValveInN2},
                                {StatusName.右侧放空总管1,-1},
                                {StatusName.右侧放空总管2,-1},
                                {StatusName.右侧放空总管3,-1},
                                {StatusName.气相丙烯回收1,-1},
                                {StatusName.气相丙烯回收2,-1},
                                {StatusName.气相丙烯回收3,-1},
                                {StatusName.右侧精致丙烯总管,ValveInPropyleneRight},
                                {StatusName.右侧去丙烯回收系统,ValveOutPropylene},
                                {StatusName.右侧去丙烯回收系统从料斗, ValveEmptyFromHopper},
                                {StatusName.右侧去高点放空总管,ValveOutO2},
                                {StatusName.右侧料斗下料阀,ValveRightHopper},

                                {StatusName.左侧丙烯重量1,-1},
                                {StatusName.左侧丙烯重量2,-1},
                                {StatusName.左侧氮气阀,ValveInN2Left},
                                {StatusName.左侧放空阀,ValveLeftEmpty},
                                {StatusName.左侧活化剂进料阀,ValveInActivator},
                                {StatusName.左侧活化剂料斗阀,ValveLeftHopper},
                                {StatusName.左侧活化剂压力,_pressure_hopper},
                                {StatusName.左侧精致丙烯进料阀,ValveInPropylene},
                                {StatusName.左侧气相丙烯回收阀,ValveOutGas},
                                {StatusName.左侧氢气压力,_pressure_h2},
                                {StatusName.搅拌开关,ValveStir},
                        },
                        Date = now
                    };

                    #region 计算置换
                    switch (_replace_count)
                    {
                        case 1:
                            step.Status[StatusName.气相丙烯阀1] = ValveInGas;
                            if (_can_open_empty)
                            {
                                if (_pressure_value == 0 && ValveOutGas == open)
                                {
                                    //step.status[StatusName.右侧放空总管1] = ValveOutO2;
                                    step.Status[StatusName.气相丙烯回收1] = ValveOutGas;
                                    _replace_count = 2;
                                    _can_open_empty = false;
                                }
                            }
                            break;
                        case 2:
                            step.Status[StatusName.气相丙烯阀2] = ValveInGas;
                            if (_can_open_empty)
                            {
                                if (_pressure_value == 0 && ValveOutGas == open)
                                {
                                    //step.status[StatusName.右侧放空总管2] = ValveOutO2;
                                    step.Status[StatusName.气相丙烯回收2] = ValveOutGas;
                                    _replace_count = 3;
                                    _can_open_empty = false;
                                }
                            }
                            break;
                        case 3:
                            step.Status[StatusName.气相丙烯阀3] = ValveInGas;
                            if (_can_open_empty)
                            {
                                if (_pressure_value == 0 && ValveOutGas == open)
                                {
                                    //step.Status[StatusName.右侧放空总管3] = ValveOutO2;
                                    step.Status[StatusName.气相丙烯回收3] = ValveOutGas;
                                    _replace_count = 4;
                                    _can_open_empty = false;
                                }
                            }
                            break;
                        default:
                            break;
                    }

                    switch (_propylene_number)
                    {
                        case 1:
                            step.Status[StatusName.左侧丙烯重量1] = _weight_left1;
                            if (_can_fill_second_propylene)
                            {
                                _propylene_number = 2;
                                _can_fill_propylene = false;
                            }
                            break;
                        case 2:
                            step.Status[StatusName.左侧丙烯重量2] = _weight_left2;
                            if (_can_fill_propylene)
                            {
                                _propylene_number = 3;

                            }
                            break;
                        default:
                            break;
                    }

                    #endregion
                    _isListenSingnalover = true;
                    _steps.Add(step);
                    Thread.Sleep(_sleepfast);
                }
            });
            t.Start();
        }

        int valveLeftEmpty = -1,
                        valveOutO2 = -1,
                        valveInActivator = -1,
                        _valveInCold = -1,
                        _valveInColdSecond = -1,
                        _valveInGas = -1,
                        _valveInH2 = -1,
                        _valveInHot = -1,
                        _valveInN2Right = -1,
                        _valveInN2Left = -1,
                        _valveInPropyleneLeft = -1,
                        _valveInPropyleneRight = -1,
                        _valveLeftHopper = -1,
                        _valveOutGas = -1,
                        _valveOutPropylene = -1,
                        _valveOutPropyleneWithHopper = -1,
                        _valveRightHopper = -1,
                        _valveEmptyFromHopper = -1,
                        valveStir = -1,
                        valveStop = -1;

        private void ParseSpData(string data)
        {
            #region 165协议
            Match match = Regex.Match(data, @"\d{5}_\d{3}");
            if (match.Success)
            {
                string s = match.Groups[0].Value.Split('_')[1];
                int v = Convert.ToInt32(s);
                string r = Convert.ToString(v, 2).PadLeft(8, '0');
                string prefix = match.Groups[0].Value.Split('_')[0];

                #region 解析数据

                if (prefix == _prefix1)
                {
                    _valveOutPropylene = Convert.ToInt32(r[0]);
                    _valveInGas = Convert.ToInt32(r[1]);
                    valveStop = Convert.ToInt32(r[2]);
                    valveStir = Convert.ToInt32(r[3]);
                    //_valveEmptyFromHopper = Convert.ToInt32(r[4]);
                    _valveOutGas = Convert.ToInt32(r[5]);
                    valveInActivator = Convert.ToInt32(r[6]);
                    valveOutO2 = Convert.ToInt32(r[7]);

                    _valveOutPropyleneState = _valveOutPropylene == open;
                    _valveInGasState = _valveInGas == open;
                    _valveStopState = valveStop == open;
                    _valveStirState = valveStir == open;
                    //ValveEmptyFromHopper_State = valveEmptyFromHopper == open;
                    _valveOutGas_State = _valveOutGas == open;
                    _valveInActivatorState = valveInActivator == open;
                    _valveOutO2State = valveOutO2 == open;

                    _isgetoverstate1 = true;
                }
                else if (prefix == _prefix2)
                {
                    _valveInPropyleneRight = Convert.ToInt32(r[0]);
                    valveLeftEmpty = Convert.ToInt32(r[2]);
                    _valveInPropyleneLeft = Convert.ToInt32(r[3]);
                    _valveInHot = Convert.ToInt32(r[5]);

                    _valveInPropyleneRightState = _valveInPropyleneRight == open;
                    _valveLeftEmptyState = valveLeftEmpty == open;
                    _valveInPropyleneLeftState = _valveInPropyleneLeft == open;
                    _valveInHotState = _valveInHot == open;
                    _isgetoverstate2 = true;
                }
                else if (prefix == _prefix3)
                {
                    _valveInH2 = Convert.ToInt32(r[0]);
                    _valveRightHopper = Convert.ToInt32(r[1]);
                    _valveOutPropyleneWithHopper = Convert.ToInt32(r[2]);
                    _valveLeftHopper = Convert.ToInt32(r[3]);
                    _valveInN2Right = Convert.ToInt32(r[4]);
                    _valveInColdSecond = Convert.ToInt32(r[5]);
                    _valveInCold = Convert.ToInt32(r[6]);
                    _valveInN2Left = Convert.ToInt32(r[7]);

                    _valveInH2State = _valveInH2 == open;
                    _valveRightHopperState = _valveRightHopper == open;
                    _valveOutPropyleneWithHopperState = _valveOutPropyleneWithHopper == open;
                    _valveLeftHopperState = _valveLeftHopper == open;
                    _valveInN2RightState = _valveInN2Right == open;
                    _valveInColdState = _valveInCold == open;
                    _valveInColdSecondState = _valveInColdSecond == open;

                    _isgetoverstate3 = true;
                }
                #endregion


            } 
            #endregion


            #region 添加步骤
            DateTime now = DateTime.Now;
            Step step = new Step()
            {
                Status =new Dictionary<Enum, double>()
                        {
                                {StatusName.丙烯总量,_valveInGas},
                                {StatusName.反应釜压力,_pressure_value},
                                {StatusName.冷水阀辅 , _valveInColdSecond},
                                {StatusName.冷水阀主,_valveInCold},
                                //{StatusName.冷水回水阀,valveOutCold},
                                {StatusName.气相丙烯阀1,-1},
                                {StatusName.气相丙烯阀2,-1},
                                {StatusName.气相丙烯阀3,-1},
                                {StatusName.氢气阀,_valveInH2},
                                {StatusName.热水阀,_valveInHot},
                                //{StatusName.热水回水阀,valveOutHot},
                                {StatusName.温度,_temperature_value},

                                {StatusName.右侧丙烯重量, _weight_right},
                                {StatusName.右侧氮气阀,_valveInN2Right},
                                {StatusName.右侧放空总管1,-1},
                                {StatusName.右侧放空总管2,-1},
                                {StatusName.右侧放空总管3,-1},
                                {StatusName.气相丙烯回收1,-1},
                                {StatusName.气相丙烯回收2,-1},
                                {StatusName.气相丙烯回收3,-1},
                                {StatusName.右侧精致丙烯总管,_valveInPropyleneRight},
                                {StatusName.右侧去丙烯回收系统,_valveOutPropylene},
                                {StatusName.右侧去丙烯回收系统从料斗, _valveEmptyFromHopper},
                                {StatusName.右侧去高点放空总管,valveOutO2},
                                {StatusName.右侧料斗下料阀,_valveRightHopper},

                                {StatusName.左侧丙烯重量1,-1},
                                {StatusName.左侧丙烯重量2,-1},
                                {StatusName.左侧氮气阀,_valveInN2Left},
                                {StatusName.左侧放空阀,valveLeftEmpty},
                                {StatusName.左侧活化剂进料阀,valveInActivator},
                                {StatusName.左侧活化剂料斗阀,_valveLeftHopper},
                                {StatusName.左侧活化剂压力,_pressure_hopper},
                                {StatusName.左侧精致丙烯进料阀,_valveInPropyleneLeft},
                                {StatusName.左侧气相丙烯回收阀,_valveOutGas},
                                {StatusName.左侧氢气压力,_pressure_h2},
                                {StatusName.搅拌开关,valveStir},
                        },
                Date = now
            };

            #region 计算置换
            switch (_replace_count)
            {
                case 1:
                    step.Status[StatusName.气相丙烯阀1] = _valveInGas;
                    if (_can_open_empty)
                    {
                        if (_pressure_value == 0 && _valveOutGas == open)
                        {
                            //step.Status[StatusName.右侧放空总管1] = valveOutO2;
                            step.Status[StatusName.气相丙烯回收1] = _valveOutGas;
                            _replace_count = 2;
                            _can_open_empty = false;
                        }
                    }
                    break;
                case 2:
                    step.Status[StatusName.气相丙烯阀2] = _valveInGas;
                    if (_can_open_empty)
                    {
                        if (_pressure_value == 0 && _valveOutGas == open)
                        {
                            // step.Status[StatusName.右侧放空总管2] = valveOutO2;
                            step.Status[StatusName.气相丙烯回收2] = _valveOutGas;
                            _replace_count = 3;
                            _can_open_empty = false;
                        }
                    }
                    break;
                case 3:
                    step.Status[StatusName.气相丙烯阀3] = _valveInGas;
                    if (_can_open_empty)
                    {
                        if (_pressure_value == 0 && _valveOutGas == open)
                        {
                            //step.Status[StatusName.右侧放空总管3] = valveOutO2;
                            step.Status[StatusName.气相丙烯回收3] = _valveOutGas;
                            _replace_count = 4;
                            _can_open_empty = false;
                        }
                    }
                    break;
            }

            switch (_propylene_number)
            {
                case 1:
                    step.Status[StatusName.左侧丙烯重量1] = _weight_left1;
                    if (_can_fill_second_propylene)
                    {
                        _propylene_number = 2;
                        _can_fill_propylene = false;
                    }
                    break;
                case 2:
                    step.Status[StatusName.左侧丙烯重量2] = _weight_left2;
                    if (_can_fill_propylene)
                    {
                        _propylene_number = 3;

                    }
                    break;
                default:
                    break;
            }

            #endregion
            _steps.Add(step);
            #endregion
        }


        private void _serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            try
            {
                string temp = _serialPort.ReadLine();
                Console.WriteLine("收到：\t" + temp + DateTime.Now.ToString("HH:mm:ss"));
                Task.Run(() => ParseSpData(temp));
            }
            catch (Exception)
            {
                 
            }
        }


        private void ListenOPCRelation()
        {
            //温度与压力的比例
            double rate = 3.6 / (77 - 22);
            ThreadPool.QueueUserWorkItem((o) =>
            {
                #region 左侧 精致丙烯进料
                Task.Run(() =>
                {
                    while (!_listenCts.IsCancellationRequested)
                    {
                        if (_valveInPropyleneLeftState)
                        {
                            if (!Isinner) ValveInPropyleneLeft_item.Open();
                            FlowInPropylene_item.StartFlow();

                            if (_valveLeftHopperState && _total_weight1 > 0)
                            {
                                _total_weight1 -= _flow_value;
                                LabelWeight1_item.Write(_total_weight1);//剩余量                                
                                
                                SpLeftHeightValue(_total_weight1);
                                if (_can_fill_second_propylene)
                                {
                                    _weight_left2 += _flow_value;
                                }
                                else
                                {
                                    _weight_left1 += _flow_value;
                                }
                            }
                        }
                        else
                        {
                            if (_weight_left2 > 3000)
                                _can_fill_propylene = true;

                            if (!Isinner) ValveInPropyleneLeft_item.Close();
                            FlowInPropylene_item.StopFlow();
                        }
                        Thread.Sleep(_sleepfast);
                    }
                });
                #endregion

                #region 左侧 活化物 打开 活化剂压力下降
                Task.Run(() =>
                {
                    while (!_listenCts.IsCancellationRequested)
                    {
                        if (_valveInActivatorState && _valveLeftHopperState)
                        {
                            if (!Isinner) { 
                                ValveInActivator_item.Open();
                                ValveLeftHopper_item.Open();
                            }
                            _total_pressure_hopper -= _pressure_hopper_crement;

                            if (_total_pressure_hopper > 0)
                            {
                                LabelPressureHopper_item.Write(_total_pressure_hopper);

                                _pressure_hopper += _pressure_hopper_crement;
                                _pressure_value += _pressure_hopper_crement;


                                if (_pressure_hopper > 0.1)
                                {
                                    _can_fill_second_propylene = true;
                                }

                                if (_pressure_value > 0.2)
                                {
                                    BeginWarning(WarningType.活化剂压力过高);
                                }
                                LabelPressure_item.Write(_pressure_value);
                                SpPressureValue(_pressure_value);
                            }
                            else
                            {
                                _total_pressure_hopper = 0;
                            }
                            FlowInActivator_item.StartFlow();
                        }
                        else
                        {
                            StopWarning(WarningType.活化剂压力过高);
                            if (!Isinner) ValveInActivator_item.Close();
                            FlowInActivator_item.StopFlow();
                        }
                        Thread.Sleep(_sleepfast);
                    }
                });

                #endregion

                #region 左侧 加料斗
                //Task.Run(() =>
                // {
                //     while (!_listenCts.IsCancellationRequested)
                //     {
                //         if (ValveLeftHopper_State)
                //         {
                //             //ValveLeftHopper_item.Open();
                //             FlowInLeft_item.StartFlow();
                //         }
                //         else
                //         {
                //             //ValveLeftHopper_item.Close();
                //             FlowInLeft_item.StopFlow();
                //         }
                //         Thread.Sleep(_sleepfast);
                //     }
                // });
                #endregion

                #region 左侧 气相丙烯回收
                Task.Run(() =>
                {
                    while (!_listenCts.IsCancellationRequested)
                    {
                        if (_valveOutGas_State && _valveLeftHopperState)
                        {
                            if (!Isinner) ValveOutGas_item.Open();
                            FlowOutGas_item.StartFlow();

                            _pressure_value = Math.Round(_pressure_value, 2);

                            if (_pressure_value < 0.05)
                                _pressure_decrement = 0.01;
                            else if (_pressure_value < 0.1)
                                _pressure_decrement = 0.02;
                            else
                                _pressure_decrement = 0.07;

                            //_pressure_decrement = _pressure_value <= 0.05 ? 0.01 : 0.05;
                            _pressure_value -= _pressure_decrement;
                            if (_pressure_value >= 0.01)
                            {
                                LabelPressure_item.Write(_pressure_value);
                                SpPressureValue(_pressure_value);
                            }
                            else
                            {
                                _pressure_value = 0;
                                LabelPressure_item.Write(_pressure_value);
                                FlashPressure_item.Close();
                            }
                        }
                        else
                        {
                            if (!Isinner) ValveOutGas_item.Close();
                            FlowOutGas_item.StopFlow();
                            FlashPressure_item.Close();
                        }
                        Thread.Sleep(_sleepfast);
                    }

                });
                #endregion

                #region 左侧 放空管道
                Task.Run(() =>
                {
                    while (!_listenCts.IsCancellationRequested)
                    {
                        if (_valveLeftEmptyState)
                        {
                            _pressure_decrement = _pressure_value < 0.05 ? 0.01 : 0.04;
                            if (!Isinner) ValveLeftEmpty_item.Open();
                            FlowLeftEmpty_item.StartFlow();

                            if (_valveLeftHopperState)
                            {
                                _pressure_value-=_pressure_decrement;
                                if (_pressure_value > 0)
                                {
                                    LabelPressure_item.Write(_pressure_value);
                                    SpPressureValue(_pressure_value);
                                }
                                else
                                {
                                    _pressure_value = 0;
                                    LabelPressure_item.Write(_pressure_value);
                                }
                            }
                        }
                        else
                        {
                            if (!Isinner) ValveLeftEmpty_item.Close();
                            FlowLeftEmpty_item.StopFlow();
                        }
                        Thread.Sleep(_sleepfast);
                    }
                });
                #endregion
               
                #region 左侧 气相丙烯
                Task.Run(() => {
                    while (!_listenCts.IsCancellationRequested)
                    {
                        if (_valveInGasState)
                        {
                            _pressure_increment = 0.03;//0.05
                            if (!Isinner) ValveInGas_item.Open();
                            FlowInGas_item.StartFlow();
                            _pressure_value += _pressure_increment;
                            LabelPressure_item.Write(_pressure_value);
                            SpPressureValue(_pressure_value);
                            if (_pressure_value > 0.6)//1.1
                                BeginWarning(WarningType.气相丙烯压力过高);

                            if (_pressure_value>0.2)//0.5;
                            {
                                _can_open_empty = true;
                            }
                        }
                        else
                        {
                            if (!Isinner) ValveInGas_item.Close();
                            StopWarning(WarningType.气相丙烯压力过高);
                            FlowInGas_item.StopFlow();
                        }
                        Thread.Sleep(_sleepfast);
                    }
                });
                #endregion

                #region 左侧 氢气
                Task.Run(() =>
                {
                    while (!_listenCts.IsCancellationRequested)
                    {
                        if (_valveInH2State)
                        {
                            _pressure_increment = 0.01;
                            if (!Isinner) ValveInH2_item.Open();
                            FlowInH2_item.StartFlow();
                            _total_pressure_h2 -= _pressure_increment;
                            _h2_flow += _h2_flow_crement;

                            if (_total_pressure_h2 > 0)
                            {
                                LabelH2press_item.Write(_total_pressure_h2);
                                _pressure_value += _pressure_increment;
                                LabelPressure_item.Write(_pressure_value);
                                SpPressureValue(_pressure_value);


                                SpFlowValue(_h2_flow);

                            }

                            if (_pressure_value > 0.15)
                            {
                                BeginWarning(WarningType.氢气压力过高);
                            }
                        }
                        else
                        {
                            StopWarning(WarningType.氢气压力过高);
                            if (!Isinner) ValveInH2_item.Close();
                            FlowInH2_item.StopFlow();
                            SpFlowValue(0);
                        }
                        Thread.Sleep(_sleepfast);
                    }
                });
                #endregion


                #region 右侧 放空总管 +
                Task.Run(() => {
                    while (!_listenCts.IsCancellationRequested)
                    {
                        if (_valveOutO2State)
                        {
                            if (!Isinner) ValveOutO2_item.Open();
                            FlowOutO2_item.StartFlow();
                            _pressure_decrement = _pressure_value < 0.05 ? 0.01 : 0.04;
                            _pressure_value = Math.Round(_pressure_value, 2);
                            _pressure_value -= _pressure_decrement;

                            


                            if (_pressure_value >= 0.01)
                            {
                                LabelPressure_item.Write(_pressure_value);
                                SpPressureValue(_pressure_value);
                            }
                            else
                            {
                                _pressure_value = 0;
                                LabelPressure_item.Write(_pressure_value);
                                FlashPressure_item.Close();
                            }
                        }
                        else
                        {
                            if (!Isinner) ValveOutO2_item.Close();
                            FlowOutO2_item.StopFlow();
                            FlashPressure_item.Close();
                        }
                        Thread.Sleep(_sleepfast);
                    }
                });
                #endregion

                #region 右侧 氮气阀
                Task.Run(() =>
                {
                    while (!_listenCts.IsCancellationRequested)
                    {
                        if (_valveInN2RightState)
                        {
                            _pressure_increment = 0.01;
                            if (!Isinner) ValveInN2Right_item.Open();
                            FlowInN2_item.StartFlow();
                            if (_valveRightHopperState)
                            {
                                _pressure_value += _pressure_increment;
                                LabelPressure_item.Write(_pressure_value);
                                SpPressureValue(_pressure_value);
                            }
                            
                        }
                        else
                        {
                            if (!Isinner) ValveInN2Right_item.Close();
                            FlowInN2_item.StopFlow();
                        }
                        Thread.Sleep(_sleepfast);
                    }
                });
                #endregion


                #region 右侧 精致丙烯进料
                Task.Run(() =>
                {
                    while (!_listenCts.IsCancellationRequested)
                    {
                        if (_valveInPropyleneRightState)
                        {
                            if (!Isinner) ValveInPropyleneRight_item.Open();
                            FlowInPropyleneRight_item.StartFlow();

                            if(_valveRightHopperState && _total_weight2>0)
                            {                                
                                _total_weight2 -= _flow_value;

                                if (_total_weight2 > 0)
                                {
                                    LabelWeight2_item.Write(_total_weight2);
                                    _weight_right += _flow_value;
                                    SpRightHeightValue(_total_weight2);                                    
                                }
                                

                            }
                        }
                        else
                        {
                            if (!Isinner) ValveInPropyleneRight_item.Close();
                            FlowInPropyleneRight_item.StopFlow();
                        }
                        Thread.Sleep(_sleepfast);
                    }
                });
                #endregion

                

                #region 右侧 去丙烯回收
                Task.Run(() =>
                {
                    while (!_listenCts.IsCancellationRequested)
                    {
                        if (_valveOutPropyleneWithHopperState)
                        {
                            FlowOutPropylene_item.StartFlow();
                        }
                        else
                        {
                            FlowOutPropylene_item.StopFlow();
                        }
                        Thread.Sleep(_sleepfast);
                    }
                });
                #endregion

                #region 右侧 加料斗
                Task.Run(() =>
                {
                    //while (!_listenCts.IsCancellationRequested)
                    //{
                    //    if (ValveRightHopper_State)
                    //    {
                    //        //FlowInRight_item.StartFlow();
                    //    }
                    //    else
                    //    {
                    //        //FlowInRight_item.StopFlow();
                    //    }
                    //    Thread.Sleep(_sleepfast);
                    //}
                });
                #endregion

                #region 右侧 去丙烯回收系统 从反应釜 黄色管道
                Task.Run(() =>
                {
                    while (!_listenCts.IsCancellationRequested)
                    {
                        if (_valveOutPropyleneState)
                        {
                            if (!Isinner) ValveOutPropylene_item.Open();
                            FlowOutGasFomKettle_item.Open();
                             
                        }
                        else
                        {
                            if (!Isinner) ValveOutPropylene_item.Close();
                            FlowOutGasFomKettle_item.StopFlow();
                        }
                        Thread.Sleep(_sleepfast);
                    }
                });
                #endregion

                #region 冷水主

                ColdInHelper();
                #endregion

                #region 冷水辅
                ColdInHelperSecond(); 
                #endregion

                #region 热水阀
                Task.Run(() =>
                {
                    while (!_listenCts.IsCancellationRequested)
                    {
                        
                        if (_valveInHotState)
                        {
                            if (!Isinner) ValveInHot_item.Open();
                            FlowInHot_item.StartFlow();
                            _temperature_value += _temperature_increment;
                            _pressure_value += _pressure_increment;
                            
                            if (_temperature_value > 80)
                            {
                                _temperature_increment = 0.1;
                                _pressure_increment = rate * _temperature_increment;
                                
                            }
                            else if (_temperature_value > 70)
                            {
                                _temperature_increment = 0.5;
                                _pressure_increment = rate * _temperature_increment;
                                
                            }
                            else if (_temperature_value > 60)
                            { 
                                _temperature_increment = 1;
                                _pressure_increment = rate * _temperature_increment;
                            }
                            else
                            { 
                                _temperature_increment = 2;
                                _pressure_increment = rate * _temperature_increment;
                            }

                            if (_pressure_value > 3.8)
                            {
                                _pressure_increment = 0;
                            }

                          

                            if (_temperature_value > 90)
                            {
                                _temperature_increment = 0;
                                _pressure_increment = 0;
                                FlashTemperature_item.Open();
                                BeginWarning(WarningType.反应温度过高);
                            }
                            else
                            {
                                FlashTemperature_item.Close();
                                StopWarning(WarningType.反应温度过高);
                            }

                            LabelPressure_item.Write(_pressure_value);
                            LabelTemperature_item.Write(_temperature_value);
                            SpPressureValue(_pressure_value);
                            SpTemperatureValue(_temperature_value);

                            //todo:泄漏
                            if (_isleakAbnormal && _temperature_value >= 72)
                            {
                                BeginLeakAbnormal();
                            }
                        }
                        else
                        {
                            if (_temperature_value < 80)
                            {
                                FlashTemperature_item.Close();
                                StopWarning(WarningType.反应温度过高);
                            }
                               
                            if (!Isinner) 
                                ValveInHot_item.Close();
                            FlowInHot_item.StopFlow();
                        }
                        Thread.Sleep(_sleepfast);
                    }
                });
                #endregion

                #region 不再用
                #region 冷水出
                //Task.Run(() =>
                //{
                //    while (!_listenCts.IsCancellationRequested)
                //    {
                //        if (ValveOutCold_State)
                //        {
                //            if (!Isinner) ValveOutCold_item.Open();
                //            FlowOutCold_item.StartFlow();
                //        }
                //        else
                //        {
                //            if (!Isinner) ValveOutCold_item.Close();
                //            FlowOutCold_item.StopFlow();
                //        }
                //        Thread.Sleep(_sleepfast);
                //    }
                //});
                #endregion

                #region 热水出
                //Task.Run(() =>
                //{
                //    while (!_listenCts.IsCancellationRequested)
                //    {
                //        if (ValveOutHot_State)
                //        {
                //            if (!Isinner) ValveOutHot_item.Open();
                //            FlowOutHot_item.StartFlow();
                //        }
                //        else
                //        {
                //            if (!Isinner) ValveOutHot_item.Close();
                //            FlowOutHot_item.StopFlow();
                //        }
                //        Thread.Sleep(_sleepfast);
                //    }
                //});
                #endregion
                #region 右侧 去高点放空阀
                //Task.Run(() =>
                //{
                //    while (!_listenCts.IsCancellationRequested)
                //    {
                //        if (ValveEmptyFromHopper_State)
                //        {
                //            _pressure_decrement = _pressure_value < 0.05 ? 0.01 : 0.04;
                //            if (!Isinner) ValveEmptyFromHopper_item.Open();
                //            FlowRightEmpty_item.Open();
                //            if (ValveRightHopper_State && _pressure_value>0)
                //            {
                //                _pressure_value -= _pressure_decrement;
                //                LabelPressure_item.Write(_pressure_value);
                //                SpPressureValue(_pressure_value);
                //            }

                //        }
                //        else
                //        {
                //            if (!Isinner) ValveEmptyFromHopper_item.Close();
                //            FlowRightEmpty_item.StopFlow();
                //        }
                //        Thread.Sleep(_sleepfast);
                //    }
                //});
                #endregion

                #region 左侧 氮气 （不用了）
                //Task.Run(() => {
                //    while (!_listenCts.IsCancellationRequested)
                //    {
                //        if (ValveInN2Left_State)
                //        {
                //            if (!Isinner) ValveInN2Left_item.Open();
                //            FlowInN2Left_item.StartFlow();
                //            if (ValveLeftHopper_State && ValveInActivator_State)
                //            {
                //                _pressure_value += _pressure_increment;
                //                LabelPressure_item.Write(_pressure_value);
                //            }

                //            if (_pressure_value > 0.1)
                //            {
                //                _can_fill_second_propylene = true;
                //            }
                //        }
                //        else
                //        {
                //            if (!Isinner) ValveInN2Left_item.StopFlow();
                //            FlowInN2Left_item.StopFlow();
                //        }
                //        Thread.Sleep(_sleepfast);
                //    }
                //});

                #endregion 
                #endregion

                #region 搅拌釜状态
                Task.Run(() =>
                {
                    while (!_listenCts.IsCancellationRequested)
                    {
                        if (!_valveStirState)
                        {
                            StopStir();
                        }
                        else
                        {
                            BeginStir();
                            
                            FlashKettle_item.Open();
                            Thread.Sleep(300);
                            FlashKettle_item.Close();
                            Thread.Sleep(300);
                        }
                        Thread.Sleep(_sleepfast);
                    }
                });
                #endregion
            });
        }
        void ColdInHelper()
        {
            double rate = 3.6 / (77 - 22);
            Task.Run(() =>
            {
                while (!_listenCts.IsCancellationRequested)
                {
                    if (_valveInColdState)
                    {
                        if (!Isinner) ValveInCold_item.Open();
                        FlowInCold_item.StartFlow();
                        if (_temperature_value < 90)
                        {
                            _temperature_decrement = 2;
                            _pressure_decrement = rate * _temperature_decrement;
                        }
                        if (_temperature_value < 20)
                        {
                            _temperature_decrement = 0;
                            _pressure_decrement = 0;
                        }

                        _temperature_value -= _temperature_decrement;
                        _pressure_value -= _pressure_decrement;

                        LabelTemperature_item.Write(_temperature_value);
                        SpTemperatureValue(_temperature_value);

                        if (_pressure_value < 0)
                            _pressure_value = 0;
                        LabelPressure_item.Write(_pressure_value);
                        SpPressureValue(_pressure_value);

                    }
                    else
                    {
                        if (!Isinner) ValveInCold_item.Close();
                        FlowInCold_item.StopFlow();
                    }
                    Thread.Sleep(_sleepfast);
                }
            });
        }

        private void ColdInHelperSecond()
        {
            double rate = 3.6 / (77 - 22);
            Task.Run(() =>
            {
                while (!_listenCts.IsCancellationRequested)
                {
                    if (_valveInColdSecondState)
                    {
                        if (!Isinner) ValveInColdSecond_item.Open();
                        FlowInColdSecond_item.StartFlow();
                        if (_temperature_value < 90)
                        {
                            _temperature_decrement = 2;
                            _pressure_decrement = rate * _temperature_decrement;
                        }
                        if (_temperature_value < 20)
                        {
                            _temperature_decrement = 0;
                            _pressure_decrement = 0;
                        }

                        _temperature_value -= _temperature_decrement;
                        _pressure_value -= _pressure_decrement;

                        LabelTemperature_item.Write(_temperature_value);
                        SpTemperatureValue(_temperature_value);

                        if (_pressure_value < 0)
                            _pressure_value = 0;
                        LabelPressure_item.Write(_pressure_value);
                        SpPressureValue(_pressure_value);
                    }
                    else
                    {
                        if (!Isinner) ValveInColdSecond_item.Close();
                        FlowInColdSecond_item.StopFlow();
                    }
                    Thread.Sleep(_sleepfast);
                }
            });
        }

        private void ListenOPCRelationFast()
        {
            //温度与压力的比例
            double rate = 3.6 / (77 - 22);
            ThreadPool.QueueUserWorkItem((o) =>
            {
                #region 左侧 精致丙烯进料
                Task.Run(() =>
                {
                    while (!_listenCts.IsCancellationRequested)
                    {
                        if (_valveInPropyleneLeftState)
                        {
                            if (!Isinner) ValveInPropyleneLeft_item.Open();
                            FlowInPropylene_item.StartFlow();

                            if (_valveLeftHopperState && _total_weight1 > 0)
                            {
                                _total_weight1 -= _flow_value;
                                LabelWeight1_item.Write(_total_weight1);//剩余量                                

                                SpLeftHeightValue(_total_weight1);
                                if (_can_fill_second_propylene)
                                {
                                    _weight_left2 += _flow_value;
                                }
                                else
                                {
                                    _weight_left1 += _flow_value;
                                }
                            }
                        }
                        else
                        {
                            if (_weight_left2 > 3000)
                                _can_fill_propylene = true;

                            if (!Isinner) ValveInPropyleneLeft_item.Close();
                            FlowInPropylene_item.StopFlow();
                        }
                        Thread.Sleep(_sleepfast);
                    }
                });
                #endregion

                #region 左侧 活化物 打开 活化剂压力下降
                Task.Run(() =>
                {
                    while (!_listenCts.IsCancellationRequested)
                    {
                        if (_valveInActivatorState && _valveLeftHopperState)
                        {
                            if (!Isinner)
                            {
                                ValveInActivator_item.Open();
                                ValveLeftHopper_item.Open();
                            }
                            _total_pressure_hopper -= _pressure_hopper_crement;

                            if (_total_pressure_hopper > 0)
                            {
                                LabelPressureHopper_item.Write(_total_pressure_hopper);

                                _pressure_hopper += _pressure_hopper_crement;
                                _pressure_value += _pressure_hopper_crement;


                                if (_pressure_hopper > 0.1)
                                {
                                    _can_fill_second_propylene = true;
                                }

                                if (_pressure_value > 0.2)
                                {
                                    BeginWarning(WarningType.活化剂压力过高);
                                }
                                LabelPressure_item.Write(_pressure_value);
                                SpPressureValue(_pressure_value);
                            }
                            else
                            {
                                _total_pressure_hopper = 0;
                            }
                            FlowInActivator_item.StartFlow();
                        }
                        else
                        {
                            StopWarning(WarningType.活化剂压力过高);
                            if (!Isinner) ValveInActivator_item.Close();
                            FlowInActivator_item.StopFlow();
                        }
                        Thread.Sleep(_sleepfast);
                    }
                });

                #endregion

      

                #region 左侧 气相丙烯回收
                Task.Run(() =>
                {
                    while (!_listenCts.IsCancellationRequested)
                    {
                        if (_valveOutGas_State && _valveLeftHopperState)
                        {
                            if (!Isinner) ValveOutGas_item.Open();
                            FlowOutGas_item.StartFlow();

                            _pressure_value = Math.Round(_pressure_value, 2);

                            if (_pressure_value < 0.05)
                                _pressure_decrement = 0.01;
                            else if (_pressure_value < 0.1)
                                _pressure_decrement = 0.02;
                            else
                                _pressure_decrement = 0.07;

                            //_pressure_decrement = _pressure_value <= 0.05 ? 0.01 : 0.05;
                            _pressure_value -= _pressure_decrement;
                            if (_pressure_value >= 0.01)
                            {
                                LabelPressure_item.Write(_pressure_value);
                                SpPressureValue(_pressure_value);
                            }
                            else
                            {
                                _pressure_value = 0;
                                LabelPressure_item.Write(_pressure_value);
                                FlashPressure_item.Close();
                            }
                        }
                        else
                        {
                            if (!Isinner) ValveOutGas_item.Close();
                            FlowOutGas_item.StopFlow();
                            FlashPressure_item.Close();
                        }
                        Thread.Sleep(_sleepfast);
                    }

                });
                #endregion

                #region 左侧 放空管道
                Task.Run(() =>
                {
                    while (!_listenCts.IsCancellationRequested)
                    {
                        if (_valveLeftEmptyState)
                        {
                            _pressure_decrement = _pressure_value < 0.05 ? 0.01 : 0.04;
                            if (!Isinner) ValveLeftEmpty_item.Open();
                            FlowLeftEmpty_item.StartFlow();

                            if (_valveLeftHopperState)
                            {
                                _pressure_value -= _pressure_decrement;
                                if (_pressure_value > 0)
                                {
                                    LabelPressure_item.Write(_pressure_value);
                                    SpPressureValue(_pressure_value);
                                }
                                else
                                {
                                    _pressure_value = 0;
                                    LabelPressure_item.Write(_pressure_value);
                                }
                            }
                        }
                        else
                        {
                            if (!Isinner) ValveLeftEmpty_item.Close();
                            FlowLeftEmpty_item.StopFlow();
                        }
                        Thread.Sleep(_sleepfast);
                    }
                });
                #endregion

                #region 左侧 气相丙烯
                Task.Run(() =>
                {
                    while (!_listenCts.IsCancellationRequested)
                    {
                        if (_valveInGasState)
                        {
                            _pressure_increment = 0.03;//0.05
                            if (!Isinner) ValveInGas_item.Open();
                            FlowInGas_item.StartFlow();
                            _pressure_value += _pressure_increment;
                            LabelPressure_item.Write(_pressure_value);
                            SpPressureValue(_pressure_value);
                            if (_pressure_value > 0.5)//1.1
                                BeginWarning(WarningType.气相丙烯压力过高);

                            if (_pressure_value > 0.2)//0.5;
                            {
                                _can_open_empty = true;
                            }
                        }
                        else
                        {
                            if (!Isinner) ValveInGas_item.Close();
                            StopWarning(WarningType.气相丙烯压力过高);
                            FlowInGas_item.StopFlow();
                        }
                        Thread.Sleep(_sleepfast);
                    }
                });
                #endregion

                #region 左侧 氢气
                Task.Run(() =>
                {
                    while (!_listenCts.IsCancellationRequested)
                    {
                        if (_valveInH2State)
                        {
                            _pressure_increment = 0.01;
                            if (!Isinner) ValveInH2_item.Open();
                            FlowInH2_item.StartFlow();
                            _total_pressure_h2 -= _pressure_increment;
                            _h2_flow += _h2_flow_crement;

                            if (_total_pressure_h2 > 0)
                            {
                                LabelH2press_item.Write(_total_pressure_h2);
                                _pressure_value += _pressure_increment;
                                LabelPressure_item.Write(_pressure_value);
                                SpPressureValue(_pressure_value);


                                SpFlowValue(_h2_flow);

                            }

                            if (_pressure_value > 0.15)
                            {
                                BeginWarning(WarningType.氢气压力过高);
                            }
                        }
                        else
                        {
                            StopWarning(WarningType.氢气压力过高);
                            if (!Isinner) ValveInH2_item.Close();
                            FlowInH2_item.StopFlow();
                            SpFlowValue(0);
                        }
                        Thread.Sleep(_sleepfast);
                    }
                });
                #endregion


                #region 右侧 放空总管 +
                Task.Run(() =>
                {
                    while (!_listenCts.IsCancellationRequested)
                    {
                        if (_valveOutO2State)
                        {
                            if (!Isinner) ValveOutO2_item.Open();
                            FlowOutO2_item.StartFlow();

                            _pressure_value = Math.Round(_pressure_value, 2);
                            _pressure_value -= _pressure_decrement;

                            _pressure_decrement = _pressure_value < 0.05 ? 0.01 : 0.04;


                            if (_pressure_value >= 0.01)
                            {
                                LabelPressure_item.Write(_pressure_value);
                                SpPressureValue(_pressure_value);
                            }
                            else
                            {
                                _pressure_value = 0;
                                LabelPressure_item.Write(_pressure_value);
                                FlashPressure_item.Close();
                            }
                        }
                        else
                        {
                            if (!Isinner) ValveOutO2_item.Close();
                            FlowOutO2_item.StopFlow();
                            FlashPressure_item.Close();
                        }
                        Thread.Sleep(_sleepfast);
                    }
                });
                #endregion

                #region 右侧 氮气阀
                Task.Run(() =>
                {
                    while (!_listenCts.IsCancellationRequested)
                    {
                        if (_valveInN2RightState)
                        {
                            _pressure_increment = 0.01;
                            if (!Isinner) ValveInN2Right_item.Open();
                            FlowInN2_item.StartFlow();
                            if (_valveRightHopperState)
                            {
                                _pressure_value += _pressure_increment;
                                LabelPressure_item.Write(_pressure_value);
                                SpPressureValue(_pressure_value);
                            }

                        }
                        else
                        {
                            if (!Isinner) ValveInN2Right_item.Close();
                            FlowInN2_item.StopFlow();
                        }
                        Thread.Sleep(_sleepfast);
                    }
                });
                #endregion


                #region 右侧 精致丙烯进料
                Task.Run(() =>
                {
                    while (!_listenCts.IsCancellationRequested)
                    {
                        if (_valveInPropyleneRightState)
                        {
                            if (!Isinner) ValveInPropyleneRight_item.Open();
                            FlowInPropyleneRight_item.StartFlow();

                            if (_valveRightHopperState && _total_weight2 > 0)
                            {
                                _total_weight2 -= _flow_value;

                                if (_total_weight2 > 0)
                                {
                                    LabelWeight2_item.Write(_total_weight2);
                                    _weight_right += _flow_value;
                                    SpRightHeightValue(_total_weight2);
                                }


                            }
                        }
                        else
                        {
                            if (!Isinner) ValveInPropyleneRight_item.Close();
                            FlowInPropyleneRight_item.StopFlow();
                        }
                        Thread.Sleep(_sleepfast);
                    }
                });
                #endregion



                #region 右侧 去丙烯回收
                Task.Run(() =>
                {
                    while (!_listenCts.IsCancellationRequested)
                    {
                        if (_valveOutPropyleneWithHopperState)
                        {
                            FlowOutPropylene_item.StartFlow();
                        }
                        else
                        {
                            FlowOutPropylene_item.StopFlow();
                        }
                        Thread.Sleep(_sleepfast);
                    }
                });
                #endregion

            
                #region 右侧 去丙烯回收系统 从反应釜 黄色管道
                Task.Run(() =>
                {
                    while (!_listenCts.IsCancellationRequested)
                    {
                        if (_valveOutPropyleneState)
                        {
                            if (!Isinner) ValveOutPropylene_item.Open();
                            FlowOutGasFomKettle_item.Open();

                        }
                        else
                        {
                            if (!Isinner) ValveOutPropylene_item.Close();
                            FlowOutGasFomKettle_item.StopFlow();
                        }
                        Thread.Sleep(_sleepfast);
                    }
                });
                #endregion

                #region 冷水主

                ColdInHelper();
                #endregion

                #region 冷水辅
                ColdInHelper();
                #endregion

                #region 热水阀
                Task.Run(() =>
                {
                    while (!_listenCts.IsCancellationRequested)
                    {

                        if (_valveInHotState)
                        {
                            if (!Isinner) ValveInHot_item.Open();
                            FlowInHot_item.StartFlow();
                            _temperature_value += _temperature_increment;
                            _pressure_value += _pressure_increment;

                            if (_temperature_value > 80)
                            {
                                _temperature_increment = 0.1;
                                _pressure_increment = rate * _temperature_increment;

                            }
                            else if (_temperature_value > 70)
                            {
                                _temperature_increment = 2;
                                _pressure_increment = rate * _temperature_increment;

                            }
                            else if (_temperature_value > 60)
                            {
                                _temperature_increment = 4;
                                _pressure_increment = rate * _temperature_increment;
                            }
                            else
                            {
                                _temperature_increment = 5;
                                _pressure_increment = rate * _temperature_increment;
                            }

                            if (_pressure_value > 3.8)
                            {
                                _pressure_increment = 0;
                            }



                            if (_temperature_value > 90)
                            {
                                _temperature_increment = 0;
                                _pressure_increment = 0;
                                FlashTemperature_item.Open();
                                BeginWarning(WarningType.反应温度过高);
                            }
                            else
                            {
                                FlashTemperature_item.Close();
                                StopWarning(WarningType.反应温度过高);
                            }

                            LabelPressure_item.Write(_pressure_value);
                            LabelTemperature_item.Write(_temperature_value);
                            SpPressureValue(_pressure_value);
                            SpTemperatureValue(_temperature_value);

                            if (_isleakAbnormal && _temperature_value >= 72)
                            {
                                BeginLeakAbnormal();
                            }
                        }
                        else
                        {
                            if (_temperature_value < 80)
                            {
                                FlashTemperature_item.Close();
                                StopWarning(WarningType.反应温度过高);
                            }

                            if (!Isinner)
                                ValveInHot_item.Close();
                            FlowInHot_item.StopFlow();
                        }
                        Thread.Sleep(_sleepfast);
                    }
                });
                #endregion

                #region 不再用
                #region 冷水出
                //Task.Run(() =>
                //{
                //    while (!_listenCts.IsCancellationRequested)
                //    {
                //        if (ValveOutCold_State)
                //        {
                //            if (!Isinner) ValveOutCold_item.Open();
                //            FlowOutCold_item.StartFlow();
                //        }
                //        else
                //        {
                //            if (!Isinner) ValveOutCold_item.Close();
                //            FlowOutCold_item.StopFlow();
                //        }
                //        Thread.Sleep(_sleepfast);
                //    }
                //});
                #endregion

                #region 热水出
                //Task.Run(() =>
                //{
                //    while (!_listenCts.IsCancellationRequested)
                //    {
                //        if (ValveOutHot_State)
                //        {
                //            if (!Isinner) ValveOutHot_item.Open();
                //            FlowOutHot_item.StartFlow();
                //        }
                //        else
                //        {
                //            if (!Isinner) ValveOutHot_item.Close();
                //            FlowOutHot_item.StopFlow();
                //        }
                //        Thread.Sleep(_sleepfast);
                //    }
                //});
                #endregion
                #region 右侧 去高点放空阀
                //Task.Run(() =>
                //{
                //    while (!_listenCts.IsCancellationRequested)
                //    {
                //        if (ValveEmptyFromHopper_State)
                //        {
                //            _pressure_decrement = _pressure_value < 0.05 ? 0.01 : 0.04;
                //            if (!Isinner) ValveEmptyFromHopper_item.Open();
                //            FlowRightEmpty_item.Open();
                //            if (ValveRightHopper_State && _pressure_value>0)
                //            {
                //                _pressure_value -= _pressure_decrement;
                //                LabelPressure_item.Write(_pressure_value);
                //                SpPressureValue(_pressure_value);
                //            }

                //        }
                //        else
                //        {
                //            if (!Isinner) ValveEmptyFromHopper_item.Close();
                //            FlowRightEmpty_item.StopFlow();
                //        }
                //        Thread.Sleep(_sleepfast);
                //    }
                //});
                #endregion

                #region 左侧 氮气 （不用了）
                //Task.Run(() => {
                //    while (!_listenCts.IsCancellationRequested)
                //    {
                //        if (ValveInN2Left_State)
                //        {
                //            if (!Isinner) ValveInN2Left_item.Open();
                //            FlowInN2Left_item.StartFlow();
                //            if (ValveLeftHopper_State && ValveInActivator_State)
                //            {
                //                _pressure_value += _pressure_increment;
                //                LabelPressure_item.Write(_pressure_value);
                //            }

                //            if (_pressure_value > 0.1)
                //            {
                //                _can_fill_second_propylene = true;
                //            }
                //        }
                //        else
                //        {
                //            if (!Isinner) ValveInN2Left_item.StopFlow();
                //            FlowInN2Left_item.StopFlow();
                //        }
                //        Thread.Sleep(_sleepfast);
                //    }
                //});

                #endregion
                #endregion

                #region 搅拌釜状态
                Task.Run(() =>
                {
                    while (!_listenCts.IsCancellationRequested)
                    {
                        if (!_valveStirState)
                        {
                            StopStir();
                        }
                        else
                        {
                            BeginStir();

                            FlashKettle_item.Open();
                            Thread.Sleep(300);
                            FlashKettle_item.Close();
                            Thread.Sleep(300);
                        }
                        Thread.Sleep(_sleepfast);
                    }
                });
                #endregion
            });
        }
        #endregion

        #region 处理异常的方法
        #region 温度异常

        public override void TemperatureAbnormal()
        {
            _warningDicionary.Add(WarningType.温度异常, false);
            Task.Run(() =>
            {
                while (_temperature_value < 125)
                {
                    _temperature_value += 5;
                    LabelTemperature_item.Write(_temperature_value);
                    SpTemperatureValue(_temperature_value);
                    Thread.Sleep(_sleepfast);
                }
                BeginWarning(WarningType.温度异常); 
                FlashTemperature_item.StartFlow();
                HandleTempretureAbnormal();
            });
        }

        private void HandleTempretureAbnormal()
        {
            Task.Run(
               () =>
               {
                   Parallel.Invoke(CloseHotValve, OpenColdValve);
                   StopWarning(WarningType.温度异常);
                   _warningDicionary[WarningType.温度异常] = true;
               });
        }

        private void OpenColdValve()
        {
            while (!_listenCts.IsCancellationRequested)
            {
                if (_temperature_value <= 50)
                {
                    AddCompose("处理温度异常：打开冷水阀");
                    break;
                }
                Thread.Sleep(_sleepfast);
            }
        }

        private void CloseHotValve()
        {
            while (!_listenCts.IsCancellationRequested)
            {
                if (!_valveInHotState)
                {
                    AddCompose("处理温度异常：关闭热水阀");
                    break;
                }
                Thread.Sleep(_sleepfast);
            }
        }
        #endregion



        #region 压力异常

        public override void PressureAbnormal()
        {
            _warningDicionary.Add(WarningType.压力异常, false);
            Task.Run(() =>
            {
                while (_pressure_value < 2.5)
                {
                    _pressure_value += 0.1;
                    LabelPressure_item.Write(_pressure_value);
                    SpPressureValue(_pressure_value);
                    Thread.Sleep(_sleepfast);
                }
                BeginWarning(WarningType.压力异常);
                FlashPressure_item.StartFlow();
                HandlePressureAbnormal();
            });
        }

        private void HandlePressureAbnormal()
        {
            Task.Run(
              () =>
              {
                  Parallel.Invoke(OpenAirValve, CloseHotValve4Pressure);
                  StopWarning(WarningType.压力异常);
                  _warningDicionary[WarningType.压力异常] = true;
              });
        }

        private void CloseHotValve4Pressure()
        {
            while (!_listenCts.IsCancellationRequested)
            {
                if (!_valveInHotState)
                {
                    AddCompose("处理压力异常：关闭热水阀");
                    break;
                }
                Thread.Sleep(_sleepfast);
            }
        }

        private void OpenAirValve()
        {
            _pressure_decrement = 0.02;//加快降压
            //打开放空阀
            while (!_listenCts.IsCancellationRequested)
            {
                if (_valveOutO2State)
                {
                    if (_pressure_value <= 0.01)
                    {
                        AddCompose("处理压力异常：打开放空阀");
                        break;
                    }
                }
                Thread.Sleep(_sleepfast);
            }
        }
        #endregion

        #region 泄漏

        void BeginLeakAbnormal()
        {
            _isleakAbnormal = false;
            BeginWarning(WarningType.泄漏);
            BeginLeak();
            _warningDicionary.Add(WarningType.泄漏, false);
            HandleLeakAbnormal();
        }

        private void HandleLeakAbnormal()
        {
            //打开急停按钮
            while (!_listenCts.IsCancellationRequested)
            {
                if (_valveStopState)
                {
                    AddCompose("处理泄漏异常：按下急停按钮");
                    break;
                }
                Thread.Sleep(_sleepfast);
            }
            Parallel.Invoke(
                () =>
                    {
                        while (!_listenCts.IsCancellationRequested)
                        {
                            if (!_valveInHotState )
                            {
                                AddCompose("处理泄漏异常：关闭热水阀");
                                break;
                            }
                            Thread.Sleep(_sleepfast);
                        }
                    },
                () =>
                    {
                        while (!_listenCts.IsCancellationRequested)
                        {
                            if (!_valveInColdState && !_valveInColdSecondState)
                            {
                                AddCompose("处理泄漏异常：关闭冷水阀");
                                break;
                            }
                            Thread.Sleep(_sleepfast);
                        }
                    },
                () =>
                    {
                        while (!_listenCts.IsCancellationRequested)
                        {
                            if (!_valveInPropyleneLeftState && !_valveInPropyleneRightState)
                            {
                                AddCompose("处理泄漏异常：关闭丙烯进料阀");
                                break;
                            }
                            Thread.Sleep(_sleepfast);
                        }
                    });
            StopWarning(WarningType.泄漏);
            _warningDicionary[WarningType.泄漏] = true;
        }

        #endregion
        #endregion

        #region 重写公共方法
        public override void Begin()
        {
            ListenOPCRelation();//联动
        }

        public override async Task<string> CheckDefault()
        {
            bool isOvertime = false;
            var loop = 0;
            StringBuilder builder = new StringBuilder();
           await Task.Run(() =>
            {
                if (!Isinner)
                {
                    Thread.Sleep(2000);
                    while (!_isgetoverstate1 || !_isgetoverstate2 || !_isgetoverstate3)
                    {
                        Thread.Sleep(1000);
                        loop++;
                        if (loop > 30)
                        {
                            isOvertime = true;
                            break;
                        }
                    }
                }
                else
                {
                    // Thread.Sleep(4000);
                    while (!_isListenSingnalover)
                    {
                        Thread.Sleep(_sleepfast);
                    }
                }
                

                if (_valveLeftEmptyState)
                    builder.AppendLine("左侧放空阀未关闭");
                if (_valveOutO2State)
                    builder.AppendLine("放空总阀未关闭");
                if (_valveInActivatorState)
                    builder.AppendLine("活化剂阀门未关闭");
                if (_valveInColdState)
                    builder.AppendLine("冷水阀（主）未关闭");
                if (_valveInColdSecondState)
                    builder.AppendLine("冷水阀（辅）未关闭");
                if (_valveInGasState)
                    builder.AppendLine("气相丙烯进料阀未关闭");
                if (_valveInH2State)
                    builder.AppendLine("氢气阀未关闭");
                if (_valveInHotState)
                    builder.AppendLine("热水阀未关闭");
                if (_valveInN2RightState)
                    builder.AppendLine("右侧氮气阀未关闭");
                if (_valveInPropyleneLeftState)
                    builder.AppendLine("左侧丙烯进料阀未关闭");
                if (_valveInPropyleneRightState)
                    builder.AppendLine("右侧丙烯进料阀未关闭");
                if (_valveLeftHopperState)
                    builder.AppendLine("左侧料斗下料阀门未关闭");
                if (_valveOutGas_State)
                    builder.AppendLine("气相丙烯回收阀未关闭");
                if (_valveOutPropyleneState)
                    builder.AppendLine("丙烯回收阀未关闭");
                //if (_valveOutPropyleneWithHopperState)
                //    builder.AppendLine("右侧去丙烯回收阀未关闭");
                if (_valveRightHopperState)
                    builder.AppendLine("右侧催化剂料斗阀未关闭");
                //if (ValveEmptyFromHopper_State)
                //    builder.AppendLine("右侧去高点放空阀未关闭");
                if (_valveStirState)
                    builder.AppendLine("搅拌按钮未关闭");
                if (_valveStopState)
                    builder.AppendLine("急停按钮未关闭");

                
            });

           await InitServerData();
           if (_details == null)
               builder.AppendLine("可能由于网络原因，导致获取数据失败，请点击\"确定\"按钮 尝试重新获取");
    

           if (!isOvertime) return builder.ToString();
           builder.Clear();
           builder.AppendLine("访问设备信号超时，请检查设备连接");
           return builder.ToString();
        }
        public override void Over()
        {
            Close();
            CalcFlowAndStep();
            Score = CalcScore();
            CloseAllRelay();
            Finish();
        }

        public override void Close()
        {
            this._listenCts.Cancel();
            base.Close();
            if (_serialPort != null)
            {
                _serialPort.DataReceived -= _serialPort_DataReceived;
                _serialPort.Close();
            }
        }

        void CalcFlowAndStep()
        {
            #region 计算流程
            //丙烯置换 - 气相丙烯压力1
            var gas1_in_item = _steps.Where(i => i.Status[StatusName.气相丙烯阀1] == open)
                .OrderByDescending(i => i.Status[StatusName.反应釜压力]).OrderByDescending(i => i.Date).FirstOrDefault();

            //放空压力1
            //var empty1_out_item = gas1_in_item != null ? _steps.Where(i => i.Status[StatusName.右侧放空总管1] == open && i.Date > gas1_in_item.Date)
            //    .OrderBy(i => i.Status[StatusName.反应釜压力]).OrderByDescending(i => i.Date).FirstOrDefault() : null;
            //回收丙烯  2016.04.04
            var empty1_gas_out_item = gas1_in_item != null ? _steps.Where(i => i.Status[StatusName.气相丙烯回收1] == open && i.Date > gas1_in_item.Date)
                .OrderBy(i => i.Status[StatusName.反应釜压力]).OrderByDescending(i => i.Date).FirstOrDefault() : null;
            


            //丙烯压力2
            var gas2_in_item = empty1_gas_out_item != null ? _steps.Where(i => i.Status[StatusName.气相丙烯阀2] == open && i.Date > empty1_gas_out_item.Date)
                .OrderByDescending(i => i.Status[StatusName.反应釜压力]).ThenByDescending(i => i.Date).FirstOrDefault() : null;

            //放空压力2
            //var empty2_out_item = gas2_in_item != null ? _steps.Where(i => i.Status[StatusName.右侧放空总管2] == open && i.Date > gas2_in_item.Date)
            //    .OrderBy(i => i.Status[StatusName.反应釜压力]).ThenByDescending(i => i.Date).FirstOrDefault() : null;
            //丙烯回收2
            var empty2_gas_out_item = gas2_in_item != null ? _steps.Where(i => i.Status[StatusName.气相丙烯回收2] == open && i.Date > gas2_in_item.Date)
                .OrderBy(i => i.Status[StatusName.反应釜压力]).ThenByDescending(i => i.Date).FirstOrDefault() : null;

            //丙烯压力3
            var gas3_in_item = empty2_gas_out_item != null ? _steps.Where(i => i.Status[StatusName.气相丙烯阀3] == open && i.Date > empty2_gas_out_item.Date)
               .OrderByDescending(i => i.Status[StatusName.反应釜压力]).ThenByDescending(i => i.Date).FirstOrDefault() : null;

            //放空压力3
            //var empty3_out_item = gas3_in_item != null ? _steps.Where(i => i.Status[StatusName.右侧放空总管3] == open && i.Date > gas3_in_item.Date)
            //    .OrderBy(i => i.Status[StatusName.反应釜压力]).ThenByDescending(i => i.Date).FirstOrDefault() : null;
            //丙烯回收3
            var empty3_gas_out_item = gas2_in_item != null ? _steps.Where(i => i.Status[StatusName.气相丙烯回收3] == open && i.Date > gas2_in_item.Date)
                .OrderBy(i => i.Status[StatusName.反应釜压力]).ThenByDescending(i => i.Date).FirstOrDefault() : null;


            //开搅拌 - 后面加 xx-xx都需要打开//var stir_count = empty3_out_item != null ? _steps.Where(i => i.Status[StatusName.搅拌开关] == close && i.Date > empty3_out_item.Date).Count() : -1;

            //加氢气
            //var h2_in_item = empty3_out_item != null ? _steps.Where(i => i.Status[StatusName.氢气阀] == open && i.Date > empty3_out_item.Date)
            //    .OrderByDescending(i => i.Status[StatusName.反应釜压力]).OrderByDescending(i => i.Date).FirstOrDefault() : null;
            var h2_in_item = _steps.Where(i => i.Status[StatusName.氢气阀] == open)
                .OrderByDescending(i => i.Status[StatusName.反应釜压力]).ThenByDescending(i => i.Date).FirstOrDefault();

            //左侧放空
            //var empty_leftout_item = h2_in_item != null ? _steps.Where(i => i.Status[StatusName.左侧放空阀] == open && i.Status[StatusName.左侧活化剂料斗阀] == open && i.Date > h2_in_item.Date)
            //    .OrderBy(i => i.Status[StatusName.反应釜压力]).OrderByDescending(i => i.Date).FirstOrDefault() : null;
            var empty_leftout_item = _steps.Where(i => i.Status[StatusName.左侧放空阀] == open && i.Status[StatusName.左侧活化剂料斗阀] == open)
                .OrderBy(i => i.Status[StatusName.反应釜压力]).ThenByDescending(i => i.Date).FirstOrDefault();

            //左侧 通入丙烯 

            //var p1_inleft_maxvalue = empty_leftout_item != null ? _steps.Where(i => i.Status[StatusName.左侧精致丙烯进料阀] == open
            //     && i.Date > empty_leftout_item.Date).Max(i => i.Status[StatusName.左侧丙烯重量1]) : -1;
            //var propylene1_inleft_item = empty_leftout_item != null ? _steps.Where(i => i.Status[StatusName.左侧精致丙烯进料阀] == open
            //     && i.Date > empty_leftout_item.Date && i.Status[StatusName.左侧丙烯重量1] == p1_inleft_maxvalue).OrderBy(i => i.Date).FirstOrDefault() : null;
            var p1_inleft_count = _steps.Count(i => i.Status[StatusName.左侧精致丙烯进料阀] == open);
            var p1_inleft_maxvalue = p1_inleft_count > 0
                ? _steps.Where(i => i.Status[StatusName.左侧精致丙烯进料阀] == open).Max(i => i.Status[StatusName.左侧丙烯重量1])
                : -1;
            var propylene1_inleft_item = _steps.Where(i => i.Status[StatusName.左侧精致丙烯进料阀] == open
                && empty_leftout_item != null
                 && i.Date > empty_leftout_item.Date && i.Status[StatusName.左侧丙烯重量1] == p1_inleft_maxvalue).OrderBy(i => i.Date).FirstOrDefault();


            //左侧 充氮气
            //var n2_leftin_item = propylene1_inleft_item != null ? _steps.Where(i => i.Status[StatusName.左侧氮气阀] == open
            //    && i.Date > propylene1_inleft_item.Date)
            //    .OrderByDescending(i => i.Status[StatusName.反应釜压力]).OrderByDescending(i => i.Date).FirstOrDefault() : null;
            //var n2_leftin_item =_steps.Where(i => i.Status[StatusName.左侧氮气阀] == open)
            //   .OrderByDescending(i => i.Status[StatusName.反应釜压力]).OrderByDescending(i => i.Date).FirstOrDefault();

            //通入活化剂0.1-0.2
            var activator_item = _steps.Where(i => i.Status[StatusName.左侧活化剂进料阀] == open)
                .OrderByDescending(i => i.Status[StatusName.左侧活化剂压力]).OrderByDescending(i => i.Date).FirstOrDefault();


            //左侧 第二次通入丙烯
            var p2_inleft_count = activator_item != null
                ? _steps.Count(i => i.Status[StatusName.左侧精致丙烯进料阀] == open && i.Date > activator_item.Date)
                : 0;
            var p2_inleft_maxvalue = p2_inleft_count > 0 ? _steps.Where(i => i.Status[StatusName.左侧精致丙烯进料阀] == open && i.Date > activator_item.Date).Max(i => i.Status[StatusName.左侧丙烯重量2]) : -1;
            var p2_inleft_item = p2_inleft_maxvalue != -1 ? _steps.Where(i => i.Status[StatusName.左侧精致丙烯进料阀] == open
                && i.Status[StatusName.左侧丙烯重量2] == p2_inleft_maxvalue
                && i.Date > activator_item.Date).OrderByDescending(i => i.Date).FirstOrDefault() : null;


            //右侧泄压 不做？？

            //右侧加丙烯 
            //TODO:run可以先做？
            //var propylene_inright_maxvalue = p2_inleft_item != null ? _steps.Where(i => i.Status[StatusName.右侧精致丙烯总管] == open
            //&& i.Date > p2_inleft_item.Date).Max(i => i.Status[StatusName.右侧丙烯重量]) : -1;
            //var propylene_inright_item = propylene_inright_maxvalue != -1 ? _steps.Where(i => i.Status[StatusName.右侧精致丙烯总管] == open
            //&& i.Date > p2_inleft_item.Date && i.Status[StatusName.右侧丙烯重量] == propylene_inright_maxvalue)
            //.OrderByDescending(i => i.Date).FirstOrDefault() : null;

            var propylene_inright_count = _steps.Count(i => i.Status[StatusName.右侧精致丙烯总管] == open);
            var propylene_inright_maxvalue = propylene_inright_count > 0
                ? _steps.Where(i => i.Status[StatusName.右侧精致丙烯总管] == open).Max(i => i.Status[StatusName.右侧丙烯重量])
                : -1;
            var propylene_inright_item = propylene_inright_maxvalue != -1 ?
                _steps.Where(i => i.Status[StatusName.右侧精致丙烯总管] == open
                && i.Status[StatusName.右侧丙烯重量] == propylene_inright_maxvalue)
                .OrderByDescending(i => i.Date).FirstOrDefault() : null;


            //温度平均值 >70开始记录温度
            //var temperature_avg = propylene_inright_item != null?_steps.Where(i=>i.Status[StatusName.温度]>70 
            //    && i.Status[StatusName.热水阀] == open).Average(i => i.Status[StatusName.温度]) : -1;
            var temperature_avg_count = _steps.Count(i => i.Status[StatusName.温度] > 70
                                                          && i.Status[StatusName.热水阀] == open);
            var temperature_avg = temperature_avg_count > 0
                ? _steps.Where(i => i.Status[StatusName.温度] > 70
                                    && i.Status[StatusName.热水阀] == open).Average(i => i.Status[StatusName.温度])
                : -1;



            //var pressure_avg = propylene_inright_item != null?_steps.Where(i => 
            //     i.Status[StatusName.温度] > 70
            //    && i.Status[StatusName.热水阀] == open).Average(i => i.Status[StatusName.反应釜压力]) : -1;
            var pressure_avg_count = _steps.Count(i =>
                i.Status[StatusName.温度] > 70
                && i.Status[StatusName.热水阀] == open);
            var pressure_avg = pressure_avg_count > 0 ? _steps.Where(i =>
                 i.Status[StatusName.温度] > 70
                && i.Status[StatusName.热水阀] == open).Average(i => i.Status[StatusName.反应釜压力]) : -1;

            //反应时间 >70
            //var temperature_gt70_list = propylene_inright_item != null ? _steps.Where(i => i.Status[StatusName.温度] > 70
            //    && i.Status[StatusName.热水阀] == open).ToList() : null;
            var temperature_gt70_list = _steps.Where(i => i.Status[StatusName.温度] > 70 && i.Status[StatusName.热水阀] == open).ToList();

            //温度最大值
            //var hot_temperature_maxvalue = propylene_inright_item != null ? _steps.Where(i => i.Status[StatusName.热水阀] == open
            //    && i.Date>propylene_inright_item.Date).Max(i=>i.Status[StatusName.温度]) : -1;
            //var hot_temperature_item = hot_temperature_maxvalue != -1 ? _steps.Where(
            //    i => i.Status[StatusName.热水阀] == open
            //    && i.Date > propylene_inright_item.Date 
            //    && i.Status[StatusName.温度] == hot_temperature_maxvalue)
            //    .OrderByDescending(i => i.Date).FirstOrDefault() : null;
            var hot_temperature_maxvalue_count = _steps.Count(i => i.Status[StatusName.热水阀] == open);
            var hot_temperature_maxvalue = hot_temperature_maxvalue_count > 0
                ? _steps.Where(i => i.Status[StatusName.热水阀] == open).Max(i => i.Status[StatusName.温度])
                : -1;
            var hot_temperature_item = hot_temperature_maxvalue != -1 ? _steps.Where(
                i => i.Status[StatusName.热水阀] == open
                && i.Status[StatusName.温度] == hot_temperature_maxvalue)
                .OrderByDescending(i => i.Date).FirstOrDefault() : null;

            //回收 
            //var recycle_propylene_item = hot_temperature_item != null ? _steps.Where(i => i.Status[StatusName.右侧去丙烯回收系统] == open && i.Date > hot_temperature_item.Date)
            //    .OrderByDescending(i => i.Date).FirstOrDefault() : null;
            var recycle_propylene_item = _steps.Where(i => i.Status[StatusName.右侧去丙烯回收系统] == open)
               .OrderByDescending(i => i.Date).FirstOrDefault();
             
            //回收时 平均温度
            var recycle_temperature_avg_list = recycle_propylene_item != null
                ? _steps.Where(i => i.Status[StatusName.右侧去丙烯回收系统] == open) : null;
            var recycle_temperature_avg = recycle_temperature_avg_list != null ? recycle_temperature_avg_list.Average(i => i.Status[StatusName.温度]) : -1;

            //放空后首次开搅拌的item, 回收前不能关闭
            var stir_firstopen_item = empty3_gas_out_item != null ? _steps.FirstOrDefault(i => i.Status[StatusName.搅拌开关] == open && i.Date > empty3_gas_out_item.Date) : null;
            var stir_close_count = recycle_propylene_item != null && stir_firstopen_item != null ?
                _steps.Count(i => i.Status[StatusName.搅拌开关] == close && i.Date > stir_firstopen_item.Date && i.Date < recycle_propylene_item.Date) : -1;

            #endregion

            #region 计分
            #region 1 丙烯置换
            //1 第一次丙烯置换  充气相丙烯至(0.5～1.0) MPa置换聚合釜3遍。
            //1.1 充入气相丙烯
            if (gas1_in_item != null)
            {
                var pressure = gas1_in_item.Status[StatusName.反应釜压力];
                if (pressure >= 0.6)//1
                    AddCompose("第1次丙烯置换:压力过高");
                else if (pressure >= 0.2)//0.5
                    AddCompose("第1次丙烯置换:充丙烯完成");
                else
                    AddCompose("第1次丙烯置换：未完成");
            }
            else
                AddCompose("第1次丙烯置换：未完成");
            //1.2 气相丙烯回收
            //if (empty1_out_item != null)
                if (empty1_gas_out_item != null)
            {
                var pressure = empty1_gas_out_item.Status[StatusName.反应釜压力];
                if (pressure == 0)
                    AddCompose("第1次丙烯置换:完成");
                else 
                    AddCompose("第1次丙烯置换:压力未降至0MPa");
            }
            else
                AddCompose("第1次丙烯置换:降压未完成");

            //第2次丙烯置换
            //充入气相丙烯
            if (gas2_in_item != null)
            {
                var pressure = gas2_in_item.Status[StatusName.反应釜压力];
                if (pressure >= 0.6)//1
                    AddCompose("第2次丙烯置换:压力过高");
                else if (pressure >= 0.2)//0.5
                    AddCompose("第2次丙烯置换:充丙烯完成");
                else
                    AddCompose("第2次丙烯置换：未完成");
            }
            else
                AddCompose("第2次丙烯置换：未完成");
            //气相丙烯回收
            if (empty2_gas_out_item != null)
            {
                var pressure = empty2_gas_out_item.Status[StatusName.反应釜压力];
                if (pressure == 0)
                    AddCompose("第2次丙烯置换:完成");
                else
                    AddCompose("第2次丙烯置换:压力未降至0MPa");
            }
            else
                AddCompose("第2次丙烯置换:降压未完成");

            //第3次丙烯置换
            //充入气相丙烯
            if (gas3_in_item != null)
            {
                var pressure = gas3_in_item.Status[StatusName.反应釜压力];
                if (pressure >= 0.6)//1
                    AddCompose("第3次丙烯置换:压力过高");
                else if (pressure >= 0.2)//0.5
                    AddCompose("第3次丙烯置换:充丙烯完成");
                else
                    AddCompose("第3次丙烯置换：未完成");
            }
            else
                AddCompose("第3次丙烯置换：未完成");
            //气相丙烯回收
            if (empty3_gas_out_item != null)
            {
                var pressure = empty3_gas_out_item.Status[StatusName.反应釜压力];
                if (pressure == 0)
                    AddCompose("第3次丙烯置换:完成");
                else
                    AddCompose("第3次丙烯置换:压力未降至0MPa");
            }
            else
                AddCompose("第3次丙烯置换:降压未完成");
            #endregion

            #region 加料
            //2.搅拌釜打开

            //3.加氢 0.1MPa
            if (h2_in_item != null)
            {
                var value = h2_in_item.Status[StatusName.反应釜压力];
                if (value > 0.15)
                    AddCompose("加氢：压力过高，超过0.1MPa");
                else if (value > 0.07)
                    AddCompose("加氢：完成");
                else
                    AddCompose("加氢：未完成");
            }
            else
                AddCompose("加氢：未完成");

            //4. 通入丙烯
            //4.1 放空
            if (empty_leftout_item != null)
            {
                var value = empty_leftout_item.Status[StatusName.反应釜压力];
                if (value == 0)
                    AddCompose("通入丙烯前：将压力降至0MPa，完成");
                else
                    AddCompose("通入丙烯前：未将压力降至0MPa");
            }
            else
                AddCompose("通入丙烯前：未将压力降至0MPa");
            //4.2通入 1.5t丙烯   1.5+-1
            if (p1_inleft_maxvalue != -1)
            {
                var propylene_value = p1_inleft_maxvalue;
                if (propylene_value >= 1400 && propylene_value <= 1650)
                {
                    AddCompose("通入丙烯：1.5吨完成");
                }
                else if (propylene_value > 1650)
                {
                    AddCompose("通入丙烯：丙烯含量过高");
                }
                else
                {
                    AddCompose("通入丙烯：丙烯含量不足");
                }
            }else
            {
                AddCompose("通入丙烯：通入1.5吨丙烯未完成");
            }

            //5投活化剂 加丙烯3t
            //5.1 充活化剂 0.1-0.2
            if (activator_item != null)
            {
                var activaator_value = activator_item.Status[StatusName.左侧活化剂压力];
                if (activaator_value >= 0.1 && activaator_value <= 0.2)
                {
                    AddCompose("充活化剂：0.1-0.2MPa完成");
                }
                else if (activaator_value > 0.2)
                {
                    AddCompose("充活化剂：压力超过0.2MPa");
                }
                else
                {
                    AddCompose("充活化剂：压力不足0.1MPa");
                }
            }
            else
            {
                AddCompose("充活化剂：未完成");
            }

            //5.2 充入3t丙烯
            if (p2_inleft_maxvalue != -1)
            {
                var value = p2_inleft_maxvalue;
                if (value >= 2900 && value <= 3150)
                {
                    AddCompose("通入丙烯充活化剂：3吨完成");
                }
                else if (value > 3150)
                {
                    AddCompose("通入丙烯充活化剂：丙烯含量过高");
                }
                else
                {
                    AddCompose("通入丙烯充活化剂：丙烯含量不足");
                }
            }
            else
            {
                AddCompose("通入丙烯充活化剂：3吨未完成");
            }

            //6 催化剂加丙烯 1.5
            if (propylene_inright_item != null)
            {
                var value = propylene_inright_item.Status[StatusName.右侧丙烯重量];
                if (value >= 1400 && value <= 1650)
                {
                    AddCompose("通入丙烯加催化剂：1.5吨完成");
                }
                else if (value > 1650)
                {
                    AddCompose("通入丙烯加催化剂：丙烯含量过高");
                }
                else
                {
                    AddCompose("通入丙烯加催化剂：丙烯含量不足");
                }
            }
            else
            {
                AddCompose("通入丙烯加催化剂：1.5吨未完成");
            }
            #endregion

            #region 升温
            //7 升温  
            //7.1控制反应温度77-1 (- +7)± 
            if (temperature_avg >= 70 && temperature_avg <= 84)
            {
                AddCompose("聚合升温：釜温（77±1）℃");
            }
            else
            {
                AddCompose("聚合升温：釜温不在（77±1）℃范围内");
            }
            //7.2 控制反应压力
            if (pressure_avg >= 3.2 && pressure_avg <= 4)
            {
                AddCompose("聚合升温：压力（3.6±1）MPa");
            }
            else
            {
                AddCompose("聚合升温：压力不在（3.6±1）MPa范围内");
            }
            //7.3 升温时间
            if (temperature_gt70_list.Count > 0)
            {
                var date_diff = temperature_gt70_list.Max(i => i.Date) - temperature_gt70_list.Min(i => i.Date);
                //反正时间待定
                if (date_diff.Seconds >= _reaction_second)
                {
                    AddCompose("聚合升温：反应结束");
                }
                else
                {
                    AddCompose("聚合升温：反应时间不足");
                }
            }
            else
            {
                AddCompose("聚合升温：反应时间不足");
            }
            #endregion


            #region 回收 降温
            //8 回收
            //8.1 降温
            if (recycle_temperature_avg >= 40 && recycle_temperature_avg <= 55)
            {
                AddCompose("回收丙烯：控制温度在40-55℃");
            }
            else
            {
                if (recycle_temperature_avg != -1)
                    AddCompose("回收丙烯：温度不在40-55℃之间");
            }

            //8.2 回收阀
            if (recycle_propylene_item != null)
            {
                AddCompose("回收丙烯：完成");
            }
            else
            {
                AddCompose("回收丙烯：未完成");
            }

            //8.3 关搅拌
            if (stir_close_count == 0)
            {
                AddCompose("搅拌釜：打开");
            }
            else if (stir_close_count != -1)
            {
                AddCompose("反应过程中，搅拌釜未及时打开或关闭");
            } 
            #endregion
            #endregion
        }
       
     
        #endregion

        #region 操纵继电器-预警
        void CloseAllRelay()
        {
            SPWriteTool(0);
        }
        /// <summary>
        /// 写继电器
        /// </summary>
        /// <param name="number">0-128， </param>
        void SPWriteTool(int number)
        {
            if (Isinner) return;
            WriteTool(_relaycmd, number);
        }
        private void StopWarning(WarningType type)
        {
            if (_warningtypes.Contains(type))
            {
                FlashWarning_item.Close();
                _relay_command = (~_warning1number) & _relay_command;
                _relay_command = (~_warning2number) & _relay_command;
                SPWriteTool(_relay_command);
                _warningtypes.Remove(type);
            }
        }

        private void BeginWarning(WarningType type)
        {
            if (!_warningtypes.Contains(type))
            {
                FlashWarning_item.Open();
                _warningtypes.Add(type);
                _relay_command = _relay_command | _warning1number;
                _relay_command = _relay_command | _warning2number;
                SPWriteTool(_relay_command);
            }
        }

        void BeginStir()
        {
            FlashWarning_item.Open();
            _relay_command = _relay_command | _stirnumber;
            SPWriteTool(_relay_command);
        }

        void StopStir()
        {
            FlashWarning_item.Close();
            _relay_command = _relay_command & (~_stirnumber);
            SPWriteTool(_relay_command);
        }

        void BeginLeak()
        {
            FlashWarning_item.Open();
            _relay_command = _relay_command | _fognumber;
            SPWriteTool(_relay_command);
            Thread.Sleep(500);
            StopLeak();

        }
        void StopLeak()
        {
            FlashWarning_item.Close();
            _relay_command = _relay_command & (~_fognumber);
            SPWriteTool(_relay_command);
        }

        #endregion

        #region 写串口数据
        void SpFlowValue(double value)
        {
            WriteFlowValue(_llcmd, 1, value);
            WriteAIvalue(_aicmd, 3, value);
        }

        void SpPressureValue(double value)
        {
            if (value < 0)
                LogTool.WriteInfoLog(value + "<0");

            WritePressureValue(_ylcmd, value);
            WriteAIvalue(_aicmd, 2, value);
        }

        void SpTemperatureValue(double value)
        {
            WriteTemperatureValue(_wdcmd, value);
            WriteAIvalue(_aicmd, 1, value);
        }

        void SpLeftHeightValue(double value)
        {
            WritePressureValue(_leftHeightCmd, value);
        }

        void SpRightHeightValue(double value)
        {
            WritePressureValue(_rightHeightCmd, value);
        }
        ///
        /// <summary>
        /// 丙烯重量 左侧：1，   右侧：4
        /// </summary>
        /// <param name="index">左侧：1，   右侧：4</param>
        /// <param name="value"></param>
        void SpHeightValue(int index, double value)
        {
            if (Isinner) return;
            value = Math.Round(value, 2);
            if (value < 0) return;
            string sp_pg_value = value.ToString().PadLeft(4, '0');
            string cmd_pg = string.Format(_heightcmd, index, sp_pg_value);

            lock (this)
            {
                Thread.Sleep(150);
                if (_serialPort.IsOpen)
                    _serialPort.Write(cmd_pg);
            }
        }
        #endregion

        #region 枚举定义
        enum FieldName
        {
            //阀门
            ValveLeftEmpty, ValveOutO2, ValveInActivator, ValveInCold, ValveInColdSecond, ValveInGas, ValveInH2, ValveInHot, ValveInN2Right, ValveInN2Left, ValveInPropyleneLeft,
            ValveInPropyleneRight, ValveLeftHopper, ValveOutCold, ValveOutGas, ValveOutHot, ValveOutPropylene, ValveOutPropyleneWithHopper, ValveRightHopper, ValveInDownPropylene,
            ValveEmptyFromHopper, ValveStir, FlowOutO2, ValveStop,
            //label
            LabelPressure, LabelTemperature, LabelFlow, LabelContent, LabelPressureHopper, LabelWeight1, LabelWeight2, LabelH2press,

            //flow
            FlowInPropylene, FlowInActivator, FlowInN2, FlowInN2Left, FlowInCold, FlowInColdSecond, FlowInGas, FlowInH2, FlowInHot, FlowInLeft, FlowInPropyleneRight,
            FlowInRight, FlowOutActivator, FlowLeftEmpty, FlowOutPropylene, FlowOutCold, FlowOutGas, FlowOutHot, FlowOutGasFomKettle, FlowInPropyleneDown, FlowRightEmpty,

            //flash
            FlashKettle, FlashPressure, FlashTempreture, FlashHopperPressure,
            
            FlashWarning
        } 
        enum StatusName
        {
            左侧精致丙烯进料阀,左侧活化剂进料阀,左侧气相丙烯回收阀,左侧放空阀,左侧活化剂料斗阀,左侧氮气阀,
            氢气阀,右侧氮气阀,右侧去丙烯回收系统,搅拌开关,
            右侧去高点放空总管,右侧去丙烯回收系统从料斗,右侧精致丙烯总管,右侧料斗下料阀,
            冷水阀主,冷水阀辅,热水阀,
            冷水回水阀,热水回水阀,
            反应釜压力, 温度, 丙烯总量, 左侧活化剂压力, 左侧丙烯重量1, 左侧丙烯重量2, 左侧氢气压力, 右侧丙烯重量,
            气相丙烯阀1, 右侧放空总管1, 气相丙烯阀2, 右侧放空总管2, 气相丙烯阀3, 右侧放空总管3,
            气相丙烯回收1, 气相丙烯回收2, 气相丙烯回收3,
        }

        enum WarningType
        {
            温度异常,
            压力异常,
            气相丙烯压力过高,
            通入精致丙烯过量,
            活化剂压力过高,
            反应温度过高,
            氢气压力过高,
            泄漏,
        }

	#endregion
    }
}

